如何实现客户端和服务端的互相通信呢?也就是服务端也可以发送消息给客户端,客户端也可以处理消息,就像QQ聊天一样。
客户端代码:
public class TcpClient {
public static void main(String[] args) throws IOException {
//需求:客户端发送数据给服务端,并读取服务端反馈的数据
//1、创建Socket客户端
Socket s = new Socket("192.168.0.1",10004);
//2、获取Socket输出流,写数据
OutputStream out = s.getOutputStream();
out.write("服务端我来了".getBytes());
//3、获取socket的读取流,读取服务端发回的数据
InputStream in = (InputStream) s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
String str = new String(buf,0,len);
System.out.println("收取的数据是……"+ str);
}
}
服务器端代码:
public class TcpClient {
public static void main(String[] args) throws IOException {
//需求:客户端发送数据给服务端,并读取服务端反馈的数据
//1、创建Socket客户端
Socket s = new Socket("192.168.0.1",10004);
//2、获取Socket输出流,写数据
OutputStream out = s.getOutputStream();
out.write("服务端我来了".getBytes());
//3、获取socket的读取流,读取服务端发回的数据
InputStream in = (InputStream) s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
String str = new String(buf,0,len);
System.out.println("收取的数据是……"+ str);
}
}