TCP通信实现:多发多收消息、实现可以同时接受多个客户端
作者:互联网
package com.czie.d8_socket; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.Socket; import java.util.Scanner; /** * FileName: CilentDemo * Author: lps * Date: 2022/4/20 13:12 * Sign:刘品水 Q:1944900433 */ public class CilentDemo { public static void main(String[] args) { try { System.out.println("客户端启动成功"); //Socket(String host, int port) 创建流套接字并将其连接到指定主机上的指定端口号。 Socket socket = new Socket("192.168.10.102",22222); OutputStream os = socket.getOutputStream(); //把低级的字节流包装成打印流 PrintStream ps = new PrintStream(os); //发送消息 Scanner sc = new Scanner(System.in); while (true) { System.out.println("请说:"); String msg = sc.nextLine(); ps.println(msg); ps.flush(); } //关闭资源 //socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.czie.d8_socket; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * FileName: ServerDemo * Author: lps * Date: 2022/4/20 13:12 * Sign:刘品水 Q:1944900433 */ public class ServerDemo { public static void main(String[] args) { try { System.out.println("服务端启动成功"); ServerSocket ss = new ServerSocket(22222); //定义以恶搞死循环由主线程负责不断接受客户端socket管道链接 while (true) { //每接受一个客户端socket的链接交给一个独立的子线程负责读取信息 Socket socket = ss.accept(); System.out.println(socket.getRemoteSocketAddress()+"他来了,潇洒的来了"); //开始创建独立线程处理socket new ServerReaderThread(socket).start(); } } catch (IOException e) { e.printStackTrace(); } } }
package com.czie.d8_socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; /** * FileName: ServerReaderThread * Author: lps * Date: 2022/4/20 14:26 * Sign:刘品水 Q:1944900433 */ public class ServerReaderThread extends Thread{ private Socket socket; public ServerReaderThread(Socket socket){ this.socket=socket; } @Override public void run() { try { InputStream is = socket.getInputStream(); //包装成缓冲字符输入流 BufferedReader br = new BufferedReader(new InputStreamReader(is)); //按照行读取消息 String msg; while ((msg = br.readLine()) != null) { System.out.println(socket.getRemoteSocketAddress() + "说了:" + msg); } } catch (IOException e) { System.out.println(socket.getRemoteSocketAddress()+"下线了!!"); } } }
标签:java,socket,TCP,io,new,import,多收,Socket,客户端 来源: https://www.cnblogs.com/lps1944900433/p/16169827.html