利用网络Socket和多线程实现一个双向聊天
接收键盘输入然后向对方发送消息的线程
1 package cn.com.chat; 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 10 /** 11 * 12 * @author Xiaofei 13 * 14 */ 15 public class SendMsgThread extends Thread{ 16 /** 17 * 用来接收键盘输入然后向对方发送消息的线程 18 */ 19 Socket ss = null; 20 BufferedWriter bw = null; 21 BufferedReader br = null; 22 public SendMsgThread(Socket ss){ 23 this.ss = ss; 24 try { 25 bw = new BufferedWriter(new OutputStreamWriter(ss.getOutputStream())); 26 br = new BufferedReader(new InputStreamReader(System.in)); 27 } catch (IOException e) { 28 // TODO 自动生成的 catch 块 29 e.printStackTrace(); 30 } 31 } 32 public void run(){ 33 try { 34 while(true){ 35 String str; 36 str = br.readLine(); 37 if(str.equals("exit")){ 38 System.exit(0); 39 }else{ 40 bw.write(str+"\n"); 41 bw.flush(); 42 } 43 } 44 } catch (IOException e) { 45 // TODO 自动生成的 catch 块 46 e.printStackTrace(); 47 }finally{ 48 try { 49 bw.close(); 50 br.close(); 51 } catch (IOException e) { 52 // TODO 自动生成的 catch 块 53 e.printStackTrace(); 54 } 55 } 56 } 57 }
服务端:Server
package cn.com.chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { ServerSocket server = null; Socket socket = null; BufferedReader br= null; try { server = new ServerSocket(88); socket = server.accept(); new SendMsgThread(socket).start(); br = new BufferedReader(new InputStreamReader(socket.getInputStream())); while(true){ String str = br.readLine(); System.out.println("客户端:\n"+str); } } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }finally{ try { br.close(); server.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }
客户端:Client
1 package cn.com.chat; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.net.Socket; 7 8 public class Client { 9 public static void main(String[] args) { 10 Socket socket = null; 11 BufferedReader br = null; 12 try { 13 socket = new Socket("192.168.16.111", 88); 14 System.out.println("请输入您的消息:"); 15 new SendMsgThread(socket).start(); 16 br = new BufferedReader(new InputStreamReader( 17 socket.getInputStream())); 18 while (true) { 19 String str = br.readLine(); 20 System.out.println("客户端:\n" + str); 21 } 22 } catch (IOException e) { 23 e.printStackTrace(); 24 } finally { 25 try { 26 br.close(); 27 socket.close(); 28 } catch (IOException e) { 29 // TODO 自动生成的 catch 块 30 e.printStackTrace(); 31 } 32 } 33 } 34 35 }
特别提醒一点:注意启动的顺序,现实启动服务端,再启动客户端。现有接收的服务器,客户端才能够获得服务端的端口和IP。