共同点:
服务器端都需要俩个Socket,一个用来监听,一个用来和客户端通信;
都需要绑定端口、Ip地址和协议;
不同点:
构造方法不同,C#的Socket要设置协议类型,Java的Socket的默认为Tcp协议,UDP用dategramSocketd;C#服务器端和客户端Socket的构造方法相同,Java中服务器用ServerSocket,而客户端用Socket;
JAVA 服务器端:
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
byte[] bytes = new byte[1024*1024*5];
InputStream is = socket.getInputStream();
int i = is.read(bytes);
String s = new String(bytes, 0, i);
System.out.println("连接ok"+s);
客户端:
Socket socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
socket.connect(socketAddress);
//从控制台获取要传递到服务器的文本
InputStream is = System.in;
byte[] b = new byte[1024*1024*5];
int i = is.read(b,0,b.length);
OutputStream ops = socket.getOutputStream();
ops.write(b, 0, i);
System.out.println("写出成功");
C#服务器端:
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定对应的ip地址和端口号
s.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9080));
s.Listen(2);
Socket socket = s.Accept();
byte[] bytes = new byte[1024*1024*5];
int i = socket.Receive(bytes);
ss = Encoding.UTF8.GetString(bytes,0,i);
客户端:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9080));
string t = "发送的内容";
byte[] bytes = Encoding.UTF8.GetBytes(t);
socket.Send(bytes);