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; import java.util.concurrent.*; /** * FileName: ServerDemo * Author: lps * Date: 2022/4/20 13:12 * Sign:刘品水 Q:1944900433 */ public class ServerDemo { //使用静态变量记住一个线程池对象 private static ExecutorService pool=new ThreadPoolExecutor(3,5,6, TimeUnit.SECONDS,new ArrayBlockingQueue<>(2), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); 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()+"他来了,潇洒的来了"); Runnable target=new ServerReaderRunnable(socket); pool.execute(target); } } 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: ServerReaderRunnable * Author: lps * Date: 2022/4/20 20:43 * Sign:刘品水 Q:1944900433 */ public class ServerReaderRunnable implements Runnable { private Socket socket; public ServerReaderRunnable(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() + "下线了!!"); } } }