标签:style blog io color ar os java sp for
1、Server端:
拥有一个存放与客户端连接对象的List<socket> 有一个客户端发信息后 遍历List 实现群发功能 代码如下:
1 package com.socket; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.io.PrintWriter; 7 import java.net.ServerSocket; 8 import java.net.Socket; 9 import java.util.ArrayList; 10 import java.util.List; 11 12 public class MyServer { 13 14 public static void main(String[] args) throws Exception { 15 ServerSocket ss = new ServerSocket(10002); 16 List<Socket> allClient = new ArrayList<>(); 17 System.out.println("server is starting...."); 18 while(true){ 19 Socket s = ss.accept(); 20 allClient.add(s); 21 new Thread(new ServerThread(s, allClient)).start(); 22 } 23 } 24 25 } 26 class ServerThread implements Runnable{ 27 private Socket s; 28 private List<Socket> allClient; 29 30 public ServerThread(Socket s, List<Socket> allClient) { 31 super(); 32 this.s = s; 33 this.allClient = allClient; 34 } 35 36 @Override 37 public void run() { 38 try { 39 System.out.println(s.getInetAddress().getHostAddress()+"上线了..."); 40 BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); 41 String line = null; 42 while((line = in.readLine())!=null){ 43 for(Socket soc:allClient){ 44 //向其他客户端发信息 45 if(!soc.equals(s)){ 46 PrintWriter pw = new PrintWriter(soc.getOutputStream(),true); 47 pw.println(line); 48 } 49 } 50 } 51 } catch (IOException e) { 52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 } 55 56 } 57 58 }
2、客户端:
客户端需要注意的是用户不仅可以输入,还可以随时的接受服务端发来的信息,这就要求读和写分开两个线程来操作代码如下:
1 package com.socket; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.io.PrintWriter; 7 import java.net.InetAddress; 8 import java.net.Socket; 9 10 public class Client { 11 12 public static void main(String[] args) throws IOException, Exception { 13 final Socket s = new Socket(InetAddress.getLocalHost(),10002); 14 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 PrintWriter pw = new PrintWriter(s.getOutputStream(),true); 16 String line = null; 17 new Thread(new Runnable() { 18 @Override 19 public void run() { 20 try { 21 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); 22 String str = null; 23 while((str = br.readLine())!=null){ 24 System.out.println(str); 25 } 26 } catch (IOException e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 } 31 }).start(); 32 while ((line = br.readLine())!=null){ 33 pw.println(line); 34 } 35 s.close(); 36 br.close(); 37 } 38 }
标签:style blog io color ar os java sp for
原文地址:http://www.cnblogs.com/Wen-yu-jing/p/4083136.html