大家好,又见面了,我是全栈君。
多线程回声(Echo)模型:
1 import java.io.PrintStream; 2 import java.net.ServerSocket; 3 import java.net.Socket; 4 import java.util.Scanner; 5 6 public class EchoSrever { 7 private static class MyThread implements Runnable{ 8 private Socket client; 9 public MyThread(Socket client){ 10 this.client=client; 11 } 12 @Override 13 public void run() { 14 try{ 15 Scanner scan = new Scanner(client.getInputStream()); 16 scan.useDelimiter("\n"); 17 PrintStream out = new PrintStream(client.getOutputStream()); 18 boolean flag = true; 19 while (flag) { 20 if (scan.hasNext()) { 21 String str = scan.next().trim(); 22 if ("byebye".equalsIgnoreCase(str)) { 23 out.println("BYEBYE!!!"); 24 flag = false; 25 break; 26 } 27 out.println("Echo:" + str); 28 } 29 } 30 out.close(); 31 scan.close(); 32 }catch(Exception e){ 33 34 } 35 } 36 37 } 38 public static void main(String[] args) throws Exception { 39 ServerSocket server = new ServerSocket(8888); 40 boolean flag = true; 41 while (flag) { 42 Socket client = server.accept(); 43 new Thread(new MyThread(client)).start(); 44 } 45 server.close(); 46 } 47 }
服务器端
1 import java.io.IOException; 2 import java.io.PrintStream; 3 import java.net.Socket; 4 import java.util.Scanner; 5 6 public class EchoSocket { 7 public static void main(String[] args) throws Exception, IOException { 8 Socket client = new Socket("localhost",8888); 9 Scanner keyScan = new Scanner (System.in); 10 keyScan.useDelimiter("\n"); 11 Scanner netScan = new Scanner (client.getInputStream()); 12 netScan.useDelimiter("\n"); 13 PrintStream out = new PrintStream(client.getOutputStream()); 14 boolean flag = true; 15 while(flag){ 16 System.out.println("输入要发送的内容:"); 17 String str =null; 18 if(keyScan.hasNext()){ 19 str = keyScan.next().trim(); 20 out.println(str); 21 if (netScan.hasNext()) { 22 System.out.println(netScan.next()); 23 } 24 } 25 if("byebye".equalsIgnoreCase(str)){ 26 flag=false; 27 } 28 } 29 out.close(); 30 netScan.close(); 31 keyScan.close(); 32 } 33 }
客户端代码
转载于:https://www.cnblogs.com/ak666/p/8204726.html
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/107774.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...