java客户端与C#服务端进行socket通讯 客户端发送文本信息服务端显示

2024-12-17 08:46:34
推荐回答(2个)
回答1:

import java.io.*;
import java.util.*;
import java.net.*;
public class Client { //客户端
public static void main(String args[])throws Exception
{
String clientMessage;//来自用户输入的的信息
String serverMessage; //服务器端的信息
Socket ClientSocket=new Socket("127.0.0.0",5557);//参数是本机地址和端口,客户端套接字,发起TCP连接
BufferedReader fromUser=new BufferedReader(new InputStreamReader(System.in));//字符读取流,获取从键盘输入的字符
BufferedReader fromServer=new BufferedReader(new InputStreamReader(ClientSocket.getInputStream()));//获取从服务器端的流,建立套接字输入流
DataOutputStream toServer=new DataOutputStream(ClientSocket.getOutputStream());//建立套接字输出流
clientMessage=fromUser.readLine();//读取从用户的输入
toServer.writeBytes(clientMessage);//写到服务器端
serverMessage=fromServer.readLine();//从服务器端读取
ClientSocket.close();//关闭套接字连接
}

}
import java.io.*;
import java.net.*; //服务器端
public class Server {
public static void main(String args[])throws Exception
{
String ClientMessage;
String ServerMessage;
ServerSocket serversocket=new ServerSocket(5557);//端口要和客户端对应
System.out.println("正在监听5555端口");//
while(true)
{
Socket collection=serversocket.accept();//调用accept()函数,建立TCP连接
DataInputStream fromClient=new DataInputStream(collection.getInputStream());
DataOutputStream toClient=new DataOutputStream(collection.getOutputStream());
ClientMessage=fromClient.readUTF();//接收来自客户端的信息
ServerMessage=ClientMessage.toUpperCase();//转换为大写
toClient.writeBytes(ServerMessage);//写到服务器端
System.out.println("成功建立TCP连接");
}
}

}

回答2:

//java

byte[] buffer="你好".getBytes("utf-8");//utf8
//发送buffer

//C#
byte[] buffer=//接收到数据
string s=Encoding.UTF8.GetString(buffer);