socket实现广播和客户端到客户端的通信

来源:互联网 发布:淘宝 布料 编辑:程序博客网 时间:2024/06/01 09:56
通过Socket和多线程实现广播和客户端到客户端的通信,私聊时有离线消息。 
1.服务器端 
Java代码  收藏代码
  1. package com.gjy.socket;  
  2.   
  3.   
  4. import java.io.BufferedReader;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. import java.io.PrintWriter;  
  8. import java.net.ServerSocket;  
  9. import java.net.Socket;  
  10. import java.util.HashMap;  
  11. import java.util.Iterator;  
  12. import java.util.Map;  
  13. import java.util.Set;  
  14. import java.util.Vector;  
  15.   
  16.   
  17. public class MyServers{  
  18.     static Socket socket = null;  
  19.     static Map<String,Client> clients = new HashMap<String,Client>();  
  20.     static Vector<String> privateMesg = new Vector<String>();  
  21.       
  22.     public MyServers() throws IOException{  
  23.         ServerSocket server=new ServerSocket(5678);  
  24.         System.out.println("服务器已启动......");  
  25.         while(true){   
  26.             socket = server.accept();  
  27.             Client client = new Client(socket);  
  28.             String user = client.username;  
  29.             clients.put(user,client);  
  30.             System.out.println(client.username+"建立连接");  
  31.             client.start();  
  32.             sendPrivateMsg(user,null,null,null);   
  33.         }   
  34.           
  35.     }  
  36.       
  37.     /** 
  38.      *  
  39.      * @param sender 
  40.      * @param msge 
  41.      * @param reciver 
  42.      * @param type 
  43.      * @throws IOException 
  44.      */  
  45.     public static void sendMsg(String sender,String msge,String reciver,String type) throws IOException{  
  46.       
  47.         if(type.equals("siliao")){  
  48.             paSend(sender,msge,reciver);  
  49.         }else{  
  50.             puSend(sender,msge,reciver);  
  51.         }  
  52.     }  
  53.       
  54.     /** 
  55.      * 私聊时发送离线消息 
  56.      * @param sender消息发送者    
  57.      * @param msge消息 
  58.      * @param reciver消息接者 
  59.      * @param type消息形式(公聊或私聊) 
  60.      * @throws IOException 
  61.      */  
  62.     public static void sendPrivateMsg(String sender,String msge,String reciver,String type) throws IOException{  
  63.         System.out.println("privatemsg");  
  64.         Client client = clients.get(sender);  
  65.         for(int i =0 ;i<privateMesg.size();i++){  
  66.             String mString = privateMesg.get(i);  
  67.             String st[] = mString.split(":");  
  68.             String reciverString = st[0];  
  69.             String mg = st[1]+": "+st[2];  
  70.             if(reciverString.equals(sender)){  
  71.                 client.send(mg);  
  72.             }  
  73.         }  
  74.     }  
  75.       
  76.     /** 
  77.      * 私聊时发关消息 
  78.      * @param sender消息发送者 
  79.      * @param msge消息 
  80.      * @param reciver消息接收者 
  81.      * @throws IOException 
  82.      */  
  83.     public static void paSend(String sender,String msge,String reciver) throws IOException{  
  84.           
  85.         Client msg = clients.get(reciver);  
  86.         if(msg!=null){  
  87.             msg.send(msge);  
  88.         }else{  
  89.             String mm = reciver+":"+msge;  
  90.             privateMesg.add(mm);  
  91.             Client client = clients.get(sender);  
  92.             client.send(reciver+"不在线,你所发的消息将作为离线消息发送给对方");  
  93.         }  
  94.     }  
  95.       
  96.     /** 
  97.      * 公聊时发送消息 
  98.      * @param sender消息发送者 
  99.      * @param msge消息 
  100.      * @param reciver消息接收者 
  101.      * @throws IOException 
  102.      */  
  103.     public static void puSend(String sender,String msge,String reciver) throws IOException{  
  104.           
  105.         Set<String> set = clients.keySet();  
  106.         Iterator<String> iterator = set.iterator();  
  107.         while (iterator.hasNext()) {  
  108.             String key = (String) iterator.next();  
  109.             Client client = clients.get(key);  
  110.             client.send(msge);  
  111.         }  
  112.     }  
  113.       
  114.     /** 
  115.      * 关闭通信通道 
  116.      * @param keys指定关闭某个用户的通道 
  117.      * @throws IOException 
  118.      */  
  119.     public static void close(String keys) throws IOException{  
  120.         Client client = clients.get(keys);  
  121.         if(client!=null){  
  122.             client.client=null;  
  123.             clients.remove(keys);  
  124.             socket=null;  
  125.         }  
  126.     }  
  127.       
  128.     class Client extends Thread{  
  129.         private Socket client;  
  130.         private BufferedReader in;  
  131.         private PrintWriter out;  
  132.         private String username;  
  133.       
  134.         public Client(Socket c){   
  135.             client=c;   
  136.             try{   
  137.                 in=new BufferedReader(new InputStreamReader(client.getInputStream()));   
  138.                 out=new PrintWriter(client.getOutputStream());  
  139.                 username = in.readLine();  
  140.             }catch(IOException e){   
  141.                     e.printStackTrace();  
  142.             }  
  143.         }   
  144.   
  145.         public void run(){   
  146.             try {  
  147.                 String string="";  
  148.                 while(true){  
  149.                     string=in.readLine();  
  150.                     String s[] =string.split(":");  
  151.                         if(s.length==2){  
  152.                             String me = s[0];  
  153.                             String type = me.substring(0,6);  
  154.                             String reciver = me.substring(6,me.length());  
  155.                             String mesg =s[1];  
  156.                             String messString = username+"说:"+mesg;   
  157.                             if(mesg.equals("end")){  
  158.                                 MyServers.close(username);  
  159.                                 System.out.println(username+"断开连接");  
  160.                                 break;  
  161.                             }else{  
  162.                                 System.out.println("sending........");  
  163.                                 MyServers.sendMsg(username,messString,reciver,type);  
  164.                             }  
  165.                         }  
  166.                 }  
  167.             } catch (IOException e) {  
  168.                 System.out.println(username+"开始关闭连接");  
  169.                 try {  
  170.                     close(username);  
  171.                 } catch (IOException e1) {  
  172.                     e1.printStackTrace();  
  173.                 }  
  174.                 System.out.println(username+"关闭连接");  
  175.             }  
  176.         }  
  177.           
  178.         public void send(String str) throws IOException{  
  179.             out.println(str);   
  180.             out.flush();   
  181.         }  
  182.       
  183.     }  
  184.   
  185.     public static void main(String[] args)throws IOException{   
  186.         new MyServers();  
  187.     }   
  188.   
  189. }   

2.客户端1,输入end结束通信 
Java代码  收藏代码
  1. package com.gjy.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.*;  
  8.   
  9. public class MyClient01 implements Runnable{  
  10.     static Socket socket = null;  
  11.     static PrintWriter pw = null;  
  12.     BufferedReader bufferedReader;  
  13.     Client client;  
  14.     private static String string = "";  
  15.   
  16.     public MyClient01(){  
  17.         try {  
  18.             socket = new Socket(InetAddress.getLocalHost(),5678);  
  19.             System.out.println("建立连接,输入end结束连接");  
  20.             pw = new PrintWriter(socket.getOutputStream());  
  21.             pw.println("张三");  
  22.             pw.flush();  
  23.             client = new Client(socket);  
  24.             client.start();  
  25.         } catch (Exception e) {  
  26.             System.out.println("连接不成功");  
  27.         }  
  28.     }  
  29.       
  30.     @Override  
  31.     public void run() {  
  32.         bufferedReader = new BufferedReader(new InputStreamReader(System.in));  
  33.         while (true) {  
  34.               
  35.             try {  
  36.                   
  37.                 string = bufferedReader.readLine();  
  38.   
  39.                 //输入end结束通信  
  40.                 if(string.equals("end")){  
  41.                     MyClient01.Close();  
  42.                     break;  
  43.                 }  
  44.                 if(!"".equals(string)){  
  45.                     //广播  
  46.                     pw.println(InetAddress.getLocalHost()+ ":" +string);  
  47.                     //私聊  
  48.                     //pw.println("siliao李四:"+string);  
  49.                     pw.flush();  
  50.                 }  
  51.             } catch (IOException e) {  
  52.             }  
  53.         }  
  54.     }  
  55.       
  56.     class Client extends Thread{  
  57.         Socket client;  
  58.         BufferedReader bufferedReader;  
  59.         PrintWriter printWriter;  
  60.           
  61.         public Client (Socket socket) throws IOException{  
  62.             this.client = socket;  
  63.             bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));  
  64.             printWriter = new PrintWriter(client.getOutputStream());  
  65.               
  66.         }  
  67.           
  68.         public void run(){  
  69.             String line = "" ;  
  70.             try {  
  71.                 while(true){  
  72.                     if(string.equals("end")){  
  73.                         break;  
  74.                     }  
  75.                     line = bufferedReader.readLine();  
  76.                     System.out.println(line);  
  77.                 }  
  78.                   
  79.             } catch (UnknownHostException e) {  
  80.                 e.printStackTrace();  
  81.             } catch (IOException e) {  
  82.                 System.out.println("服务器被关闭");  
  83.             }  
  84.               
  85.         }  
  86.     }  
  87.   
  88.     public static  void  Close() throws IOException{  
  89.         pw.println(InetAddress.getLocalHost() + ":" +string);  
  90.         pw.flush();  
  91.         socket = null;  
  92.     }  
  93.       
  94.     public static void main(String args[]){  
  95.         MyClient01 myClient01 = new MyClient01();  
  96.         myClient01.run();  
  97.           
  98.           
  99.     }  
  100.   
  101. }  

3.客户端2,输入end结束通信 
Java代码  收藏代码
  1. package com.gjy.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.*;  
  8.   
  9. public class MyClient02 implements Runnable{  
  10.     static Socket socket = null;  
  11.     static PrintWriter pw = null;  
  12.     BufferedReader bufferedReader;  
  13.     Client client;  
  14.     private static String string = "";  
  15.   
  16.     public MyClient02(){  
  17.         try {  
  18.             socket = new Socket(InetAddress.getLocalHost(),5678);  
  19.             System.out.println("成功建立连接,输入end结束连接");  
  20.             pw = new PrintWriter(socket.getOutputStream());  
  21.             pw.println("李四");  
  22.             pw.flush();  
  23.             client = new Client(socket);  
  24.             client.start();  
  25.         } catch (Exception e) {  
  26.             System.out.println("连接不成功");  
  27.         }  
  28.           
  29.     }  
  30.       
  31.     @Override  
  32.     public void run() {  
  33.         bufferedReader = new BufferedReader(new InputStreamReader(System.in));  
  34.         while (true) {  
  35.               
  36.             try {  
  37.                 string = bufferedReader.readLine();  
  38.                 //输入end结束通信  
  39.                 if(string.equals("end")){  
  40.                     MyClient02.Close();  
  41.                     break;  
  42.                 }  
  43.                 if(!"".equals(string)){  
  44.                     //广播  
  45.                     pw.println(InetAddress.getLocalHost()+ ":" +string);  
  46.                     //私聊  
  47.                     //pw.println("siliao张三"+ ":" +string);  
  48.                     pw.flush();  
  49.                 }  
  50.             } catch (IOException e) {  
  51.             }  
  52.         }  
  53.     }  
  54.       
  55.     class Client extends Thread{  
  56.         Socket client;  
  57.         BufferedReader bufferedReader;  
  58.         PrintWriter printWriter;  
  59.           
  60.         public Client (Socket socket) throws IOException{  
  61.             this.client = socket;  
  62.             bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));  
  63.             printWriter = new PrintWriter(client.getOutputStream());  
  64.               
  65.         }  
  66.           
  67.         public void run(){  
  68.             String line = "" ;  
  69.             try {  
  70.                 while(true){  
  71.                     if(string.equals("end")){  
  72.                         break;  
  73.                     }  
  74.                     line = bufferedReader.readLine();  
  75.                     System.out.println(line);  
  76.                 }  
  77.                   
  78.             } catch (UnknownHostException e) {  
  79.                 e.printStackTrace();  
  80.             } catch (IOException e) {  
  81.                 System.out.println("服务器被关闭");  
  82.             }  
  83.               
  84.         }  
  85.     }  
  86.   
  87.     public static  void  Close() throws IOException{  
  88.         pw.println(InetAddress.getLocalHost()+ ":" +string);  
  89.         pw.flush();  
  90.         socket = null;  
  91.     }  
  92.       
  93.     public static void main(String args[]){  
  94.         MyClient02 myClient02 = new MyClient02();  
  95.         myClient02.run();  
  96.     }  
  97.   
  98. }  
0 0
原创粉丝点击