TCP 通信多发多收
作者:互联网
public class SocketDemo01 {
public static void main(String[] args) {
try {
//1. 创建Socket通信管道请求有服务端的链接
//public Socket(String host, int port)
//参数一:服务端的IP地址
//参数二:服务端的端口
Socket socket = new Socket("127.0.0.1",9999);
//2.从socket通信管道中得到一个字节输出流, 负责发送数据
OutputStream os = socket.getOutputStream();
//3.把低级的字节流包装成打印流
PrintStream printStream = new PrintStream(os);
Scanner sc = new Scanner(System.in);
//4.发送消息
while(true){
System.out.println("请说:");
String rs = sc.nextLine();
printStream.println(rs);
printStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端
public class ACC {
public static void main(String[] args) {
try {
//1.注册端口
ServerSocket serverSocket = new ServerSocket(9999);
//2.必须调用accept方法: 等待接受客户点的Socket连接请求, 建立Socket通信管道
Socket socket = serverSocket.accept();
//3.从socket通信管道中得到一个字节输入流
InputStream is = socket.getInputStream();
//4.把字节输入流包装成缓冲字符输入流进行消息的接收
InputStreamReader inputStreamReader = new InputStreamReader(is);//转换流(将字节输入流转换成字符输入流)
BufferedReader br = new BufferedReader(inputStreamReader);
//按行读取消息
String rs;
while ((rs = br.readLine()) != null){
System.out.println(socket.getRemoteSocketAddress()+"说了"+rs);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
标签:socket,rs,TCP,public,String,new,多收,多发,Socket 来源: https://www.cnblogs.com/LZYBOK/p/16088712.html