服务端的实现
1 package com.gh.echo; 2 import java.io.*; 3 import java.net.*; 4 /** 5 * echo服务器程序 6 * 实现 不断接收字符串 ,然后返回一个echo+字符串 7 * 服务程序写成多线程 8 * @author ganhang 9 * 10 */ 11 public class EchoServerDemo { 12 public static void main(String[] args) { 13 try { 14 ServerSocket ss = new ServerSocket(8000); 15 System.out.println("服务器已启动。"); 16 int i=1; 17 while (true) { 18 System.out.println("服务器正在等待连接..."); 19 Socket s = ss.accept(); 20 new Thread(new UserThread(s),"用户"+i++).start();//来一个用户启动一个线程 21 } 22 } catch (IOException e) { 23 e.printStackTrace(); 24 } 25 } 26 } 27 /** 28 * 用户线程 29 * @author ganhang 30 */ 31 class UserThread implements Runnable{ 32 private Socket s; 33 public UserThread(Socket s) { 34 this.s=s; 35 } 36 @Override 37 public void run() { 38 System.out.println(Thread.currentThread().getName()+"-已连接"); 39 try{ 40 BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); 41 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 42 while(true){//循环读入知道读入bye 43 String info=br.readLine();//因为是读一行所以客服端发送过来的字符串必须有" "换行符 44 System.out.println(info); 45 if("".equals(info)||"bye".equals(info)){ 46 break; 47 }else{ 48 bw.write("echo:你好"+Thread.currentThread().getName()+" ");//客服端用的读一行所以这边末尾加换行符 49 bw.flush();//缓存流必须刷新 50 } 51 } 52 br.close(); 53 bw.close(); 54 }catch(IOException e){ 55 e.printStackTrace(); 56 } 57 } 58 59 }
客户端的实现
1 package com.gh.echo; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 import java.io.OutputStreamWriter; 8 import java.net.Socket; 9 import java.util.Scanner; 10 /** 11 * echo客户端 12 * 实现从控制台写字符串发送给服务器,接收服务器发回来的字符串 13 * @author ganhang 14 * 15 */ 16 public class EchoClientDemo { 17 18 public static void main(String[] args) { 19 try { 20 Socket sk=new Socket("",8000); 21 System.out.println("与服务器连接成功。"); 22 Scanner sc=new Scanner(System.in); 23 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())); 24 BufferedReader br=new BufferedReader(new InputStreamReader(sk.getInputStream())); 25 while(true){ 26 System.out.println("请输入文字:"); 27 String info=sc.next(); 28 if("bye".equals(info)){ 29 break; 30 }else{ 31 bw.write(info+" "); 32 bw.flush(); 33 System.out.println(br.readLine()); 34 } 35 } 36 bw.close(); 37 br.close(); 38 } catch (IOException e) { 39 e.printStackTrace(); 40 } 41 42 } 43 }