IOS学习之websocket使用方法

前篇: 
http://haoningabc.iteye.com/blog/2011985 
代码的git地址 
https://github.com/killinux/mysocket/tree/master/websocket/project/tomcat7servlet 


如果是使用tomcat7的模式 
1.html是客户端 
2.tomcat7的servlet对websocket协议进行了封装,里面转发给普通的socket服务端 
3.普通的socket 作为服务端 


html ----->tomcat7,servlet----->socket server 



这里纯js的客户端: 
Java代码   收藏代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
  2. <html>    
  3. <head>    
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    
  5. <title>Insert title here</title>    
  6. </head>    
  7. <script type="text/javascript">    
  8.     var ws = null;    
  9.     function startServer() {    
  10.         var url = "ws://192.168.0.102:5000";    
  11.         if ('WebSocket' in window) {    
  12.             ws = new WebSocket(url);    
  13.         } else if ('MozWebSocket' in window) {    
  14.             ws = new MozWebSocket(url);    
  15.         } else {    
  16.             alert('浏览器不支持');    
  17.             return;  
  18.         }    
  19.         ws.onopen = function() {    
  20.             alert('Opened!');    
  21.         };    
  22.         // 收到服务器发送的文本消息, event.data表示文本内容    
  23.         ws.onmessage = function(event) {    
  24.             alert('Receive message: ' + event.data);    
  25.         };    
  26.         ws.onclose = function() {    
  27.           alert('Closed!');    
  28.         }    
  29. }    
  30.     //发送信息    
  31.     function sendMessage(){    
  32.         var textMessage=document.getElementById("textMessage").value;    
  33.             
  34.         if(ws!=null&&textMessage!=""){    
  35.             ws.send(textMessage);    
  36.                 
  37.         }    
  38.     }    
  39. </script>    
  40. <body οnlοad="startServer()">    
  41.         <input type="text" id="textMessage" size="20" />    
  42.         <input type="button" οnclick="sendMessage()" value="Send">    
  43.     </body>    
  44. </html>    


如果是用java-websocket, 

git为 https://github.com/killinux/Java-WebSocket 
代码如下: 
socket server端: 
Java代码   收藏代码
  1. import java.io.DataInputStream;  
  2. import java.io.DataOutputStream;  
  3. import java.net.ServerSocket;  
  4. import java.net.Socket;  
  5. public class Server {  
  6.     public static final int PORT = 5000;  
  7.     public static void main(String[] args) {  
  8.         System.out.println("服务器...\n");  
  9.         Server ser = new Server();  
  10.         ser.sock();  
  11.     }  
  12.     public void sock() {  
  13.         try {  
  14.             ServerSocket server = new ServerSocket(PORT);  
  15.             while (true) {  
  16.                 // 一旦有堵塞, 则表示服务器与客户端获得了连接  
  17.                 Socket client = server.accept();  
  18.                 // 处理这次连接  
  19.                 new PServer(client);  
  20.             }  
  21.         } catch (Exception e) {  
  22.             System.out.println("服务器异常: " + e.getMessage());  
  23.         }  
  24.     }  
  25.   
  26.     private class PServer implements Runnable {  
  27.         private Socket socket;  
  28.         public PServer(Socket sock) {  
  29.             socket = sock;  
  30.             new Thread(this).start();  
  31.         }  
  32.         public void run() {  
  33.             System.out.println("一个客户端连接ip:" + socket.getInetAddress());  
  34.             try {  
  35.                 // 读取客户端数据  
  36.                 DataInputStream input = new DataInputStream(  
  37.                         socket.getInputStream());  
  38.                 // 向客户端发送数据  
  39.                 DataOutputStream out = new DataOutputStream(  
  40.                         socket.getOutputStream());  
  41.                 // 读取客户端数据  
  42.                 //System.out.println("客户端发过来的内容: " + input.readUTF());  
  43.                 byte[] bt = new byte[1024];  
  44.                 int leng = input.read(bt);  
  45.                 System.out.println(new String(bt, 0, leng));  
  46.                 // 发送键盘输入的一行  
  47.                 // String s = new BufferedReader(new  
  48.                 // InputStreamReader(System.in)).readLine();  
  49.                 String s = "server d shu ru";  
  50.                 out.write(s.getBytes());  
  51.                 out.flush();  
  52.                 input.close();  
  53.                 out.close();  
  54.                 socket.close();  
  55.             } catch (Exception e) {  
  56.                 System.out.println("服务器 run 异常: " + e.getMessage());  
  57.             }  
  58.         }  
  59.   
  60.     }  
  61.   
  62. }  

---------------------------------------------------------------------- 
---------------------------------------------------------------------- 
如果server是用tomcat转发 
参考 
http://blog.csdn.net/a79412906/article/details/9393515 
servlet: 
Java代码   收藏代码
  1. package com.hao;  
  2.   
  3. import java.io.DataInputStream;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.net.Socket;  
  7. import java.net.UnknownHostException;  
  8. import java.nio.ByteBuffer;  
  9. import java.nio.CharBuffer;  
  10.   
  11. import javax.servlet.http.HttpServletRequest;  
  12.   
  13. import org.apache.catalina.websocket.MessageInbound;  
  14. import org.apache.catalina.websocket.StreamInbound;  
  15. import org.apache.catalina.websocket.WebSocketServlet;  
  16.   
  17. public class HelloWorldWebSocketServlet extends WebSocketServlet {  
  18.   
  19.     protected StreamInbound createWebSocketInbound(String subProtocol,HttpServletRequest arg1) {  
  20.   
  21.         return new MessageInbound() {  
  22.   
  23.             @Override  
  24.             protected void onBinaryMessage(ByteBuffer arg0) throws IOException {  
  25.                 // TODO Auto-generated method stub  
  26.   
  27.             }  
  28.   
  29.             @Override  
  30.             protected void onTextMessage(CharBuffer message) throws IOException {  
  31.                 // TODO Auto-generated method stub  
  32.                 System.out.println("onText--->" + message.toString());  
  33.                 Socket socket;  
  34.                 String msg = "";  
  35.                 try {  
  36.                     // 向服务器利用Socket发送信息  
  37.                     socket = new Socket("192.168.1.102"5000);  
  38.                     //socket = new Socket("127.0.0.1",5000);  
  39.                     PrintWriter output = new PrintWriter(  
  40.                             socket.getOutputStream());  
  41.   
  42.                     output.write(message.toString());  
  43.                     output.flush();  
  44.   
  45.                     // 这里是接收到Server的信息  
  46.                     DataInputStream input = new DataInputStream(  
  47.                             socket.getInputStream());  
  48.                     byte[] b = new byte[1024];  
  49.                     input.read(b);  
  50.                     // Server返回的信息  
  51.                     msg = new String(b).trim();  
  52.   
  53.                     output.close();  
  54.                     input.close();  
  55.                     socket.close();  
  56.                 } catch (UnknownHostException e) {  
  57.                     e.printStackTrace();  
  58.                 } catch (IOException e) {  
  59.                     e.printStackTrace();  
  60.                 }  
  61.                 // 往浏览器发送信息  
  62.                 CharBuffer cb = CharBuffer.wrap(new StringBuilder(msg));  
  63.                 getWsOutbound().writeTextMessage(cb);  
  64.             }  
  65.         };  
  66.     }  
  67.   
  68.     public static void main(String[] args) {  
  69.         Socket socket;  
  70.         String message ="haoning";  
  71.         String msg = "";  
  72.         try {  
  73.             // 向服务器利用Socket发送信息  
  74.             socket = new Socket("192.168.0.102"5000);  
  75.             // socket = new Socket("127.0.0.1",5000);  
  76.             PrintWriter output = new PrintWriter(  
  77.                     socket.getOutputStream());  
  78.   
  79.             output.write(message.toString());  
  80.             output.flush();  
  81.   
  82.             // 这里是接收到Server的信息  
  83.             DataInputStream input = new DataInputStream(  
  84.                     socket.getInputStream());  
  85.             byte[] b = new byte[1024];  
  86.             input.read(b);  
  87.             // Server返回的信息  
  88.             msg = new String(b).trim();  
  89.   
  90.             output.close();  
  91.             input.close();  
  92.             socket.close();  
  93.         } catch (UnknownHostException e) {  
  94.             e.printStackTrace();  
  95.         } catch (IOException e) {  
  96.             e.printStackTrace();  
  97.         }  
  98.     }  
  99. }  

web.xml配置: 
Java代码   收藏代码
  1. <servlet>  
  2.       <servlet-name>wsSnake</servlet-name>  
  3.       <servlet-class>com.hao.HelloWorldWebSocketServlet</servlet-class>  
  4.     </servlet>  
  5.     <servlet-mapping>  
  6.       <servlet-name>wsSnake</servlet-name>  
  7.       <url-pattern>/websocket/test</url-pattern>  
  8.     </servlet-mapping>  

tomcat7的 
配置 
Java代码   收藏代码
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <Context crossContext="true" docBase="D:/workspace/work1/Test/webapp" path="/webs" reloadable="true">  
  3. </Context>  

中心server代码: 
Java代码   收藏代码
  1. import java.io.DataInputStream;  
  2. import java.io.DataOutputStream;  
  3. import java.net.ServerSocket;  
  4. import java.net.Socket;  
  5. public class Server {  
  6.     public static final int PORT = 5000;  
  7.     public static void main(String[] args) {  
  8.         System.out.println("服务器...\n");  
  9.         Server ser = new Server();  
  10.         ser.sock();  
  11.     }  
  12.     public void sock() {  
  13.         try {  
  14.             ServerSocket server = new ServerSocket(PORT);  
  15.             while (true) {  
  16.                 // 一旦有堵塞, 则表示服务器与客户端获得了连接  
  17.                 Socket client = server.accept();  
  18.                 System.out.println("server accept");  
  19.                 // 处理这次连接  
  20.                 new PServer(client);  
  21.             }  
  22.         } catch (Exception e) {  
  23.             System.out.println("服务器异常: " + e.getMessage());  
  24.         }  
  25.     }  
  26.   
  27.     private class PServer implements Runnable {  
  28.         private Socket socket;  
  29.         public PServer(Socket sock) {  
  30.             socket = sock;  
  31.             new Thread(this).start();  
  32.         }  
  33.         public void run() {  
  34.             System.out.println("一个客户端连接ip:" + socket.getInetAddress());  
  35.             try {  
  36.                 // 读取客户端数据  
  37.                 DataInputStream input = new DataInputStream(  
  38.                         socket.getInputStream());  
  39.                 // 向客户端发送数据  
  40.                 DataOutputStream out = new DataOutputStream(  
  41.                         socket.getOutputStream());  
  42.                 // 读取客户端数据  
  43.                 //System.out.println("客户端发过来的内容: " + input.readUTF());  
  44.                 byte[] bt = new byte[1024];  
  45.                 int leng = input.read(bt);  
  46.                 System.out.println(new String(bt, 0, leng));  
  47.                 // 发送键盘输入的一行  
  48.                 // String s = new BufferedReader(new  
  49.                 // InputStreamReader(System.in)).readLine();  
  50.                 String s = "server d shu ru";  
  51.                 out.write(s.getBytes());  
  52.                 out.flush();  
  53.                 input.close();  
  54.                 out.close();  
  55.                 socket.close();  
  56.             } catch (Exception e) {  
  57.                 System.out.println("服务器 run 异常: " + e.getMessage());  
  58.             }  
  59.         }  
  60.   
  61.     }  
  62.   
  63. }  


客户端改进如下: 
Java代码   收藏代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
  2. <html>    
  3. <head>    
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    
  5. <title>Insert title here</title>    
  6. </head>    
  7. <script type="text/javascript">    
  8.     var ws = null;  
  9.     function log(text) {  
  10.        document.getElementById("log").innerHTML = (new Date).getTime() + ": " + text +"<br>"+  document.getElementById("log").innerHTML;  
  11.     }    
  12.     function startServer() {    
  13.         var url = document.getElementById("serverip").value;// "ws://192.168.0.102:8887";    
  14.         if ('WebSocket' in window) {    
  15.             ws = new WebSocket(url);    
  16.         } else if ('MozWebSocket' in window) {    
  17.             ws = new MozWebSocket(url);    
  18.         } else {    
  19.             alert('浏览器不支持');    
  20.             return;  
  21.         }    
  22.         ws.onopen = function() {    
  23.             alert('Opened!');    
  24.         };    
  25.         // 收到服务器发送的文本消息, event.data表示文本内容    
  26.         ws.onmessage = function(event) {    
  27.             //alert('Receive message: ' + event.data);   
  28.             log('Receive message: ' + event.data);   
  29.         };    
  30.         ws.onclose = function() {    
  31.           alert('Closed!');    
  32.         }    
  33.         document.getElementById("conbtn").disabled="true";  
  34.         document.getElementById("stopbtn").removeAttribute('disabled');  
  35.     }    
  36.     //发送信息    
  37.     function sendMessage(){    
  38.         var textMessage=document.getElementById("textMessage").value;    
  39.             
  40.         if(ws!=null&&textMessage!=""){    
  41.             ws.send(textMessage);    
  42.                 
  43.         }    
  44.     }    
  45.     function stopconn(){  
  46.         ws.close();  
  47.         document.getElementById("conbtn").removeAttribute('disabled');  
  48.         document.getElementById("stopbtn").disabled="true";  
  49.     }  
  50. </script>    
  51. <body οnlοad="">    
  52.         <input id="serverip" type="text"  size="20" value="ws://192.168.0.102:8887"/>   
  53.         <input id="conbtn" type="button" οnclick="startServer()" value="open" />  
  54.         <input id="stopbtn" type="button" οnclick="stopconn()" value="stop" disabled="disabled"/>  
  55.         </br>  
  56.         <input id="textMessage" type="text"  size="20" />    
  57.         <input type="button" οnclick="sendMessage()" value="Send">    
  58.         <div id="log"></div>  
  59.     </body>    
  60. </html>    



servlet中发现,不能广播,只能单纯的返回,如果想每个浏览器都受到消息,则修改如下 
Java代码   收藏代码
  1. package com.hao;  
  2.   
  3. import java.io.DataInputStream;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.net.Socket;  
  7. import java.net.UnknownHostException;  
  8. import java.nio.ByteBuffer;  
  9. import java.nio.CharBuffer;  
  10. import java.util.ArrayList;  
  11.   
  12. import javax.servlet.http.HttpServletRequest;  
  13.   
  14. import org.apache.catalina.websocket.MessageInbound;  
  15. import org.apache.catalina.websocket.StreamInbound;  
  16. import org.apache.catalina.websocket.WebSocketServlet;  
  17. import org.apache.catalina.websocket.WsOutbound;  
  18.   
  19. public class HelloWorldWebSocketServlet extends WebSocketServlet {  
  20.     private static ArrayList mmiList  = new ArrayList();  
  21.   
  22.     protected StreamInbound createWebSocketInbound(String subProtocol,  
  23.             HttpServletRequest arg1) {  
  24.         return new MyMessageInbound();  
  25.     }  
  26.   
  27.     private class MyMessageInbound extends MessageInbound {  
  28.         WsOutbound myoutbound;  
  29.   
  30.         @Override  
  31.         public void onOpen(WsOutbound outbound) {  
  32.             try {  
  33.                 System.out.println("Open Client.");  
  34.                 this.myoutbound = outbound;  
  35.                 mmiList .add(this);  
  36.                 outbound.writeTextMessage(CharBuffer.wrap("Hello!"));  
  37.             } catch (IOException e) {  
  38.                 e.printStackTrace();  
  39.             }  
  40.         }  
  41.   
  42.         @Override  
  43.         public void onClose(int status) {  
  44.             System.out.println("Close Client.");  
  45.             mmiList .remove(this);  
  46.         }  
  47.   
  48.         @Override  
  49.         protected void onBinaryMessage(ByteBuffer arg0) throws IOException {  
  50.             // TODO Auto-generated method stub  
  51.   
  52.         }  
  53.   
  54.         @Override  
  55.         protected void onTextMessage(CharBuffer message) throws IOException {  
  56.             // TODO Auto-generated method stub  
  57.             System.out.println("onText--->" + message.toString());  
  58.             for (int i=0;i< mmiList.size();i++ ) {  
  59.                 MyMessageInbound mmib = (MyMessageInbound) mmiList.get(i);  
  60.                 CharBuffer buffer = CharBuffer.wrap(message);  
  61.                 mmib.myoutbound.writeTextMessage(buffer);  
  62.                 mmib.myoutbound.flush();  
  63.             }  
  64.               
  65.             /*Socket socket; 
  66.             String msg = ""; 
  67.             try { 
  68.                 // 向服务器利用Socket发送信息 
  69.                 socket = new Socket("192.168.0.102", 5000); 
  70.                 // socket = new Socket("127.0.0.1",5000); 
  71.                 PrintWriter output = new PrintWriter(socket.getOutputStream()); 
  72.  
  73.                 output.write(message.toString()); 
  74.                 output.flush(); 
  75.  
  76.                 // 这里是接收到Server的信息 
  77.                 DataInputStream input = new DataInputStream( 
  78.                         socket.getInputStream()); 
  79.                 byte[] b = new byte[1024]; 
  80.                 input.read(b); 
  81.                 // Server返回的信息 
  82.                 msg = new String(b).trim(); 
  83.  
  84.                 output.close(); 
  85.                 input.close(); 
  86.                 socket.close(); 
  87.             } catch (UnknownHostException e) { 
  88.                 e.printStackTrace(); 
  89.             } catch (IOException e) { 
  90.                 e.printStackTrace(); 
  91.             } 
  92.             // 往浏览器发送信息 
  93.             CharBuffer cb = CharBuffer.wrap(new StringBuilder(msg)); 
  94.             getWsOutbound().writeTextMessage(cb);*/  
  95.         }  
  96.     }  
  97.   
  98.     public static void main(String[] args) {  
  99.         Socket socket;  
  100.         String message = "haoning";  
  101.         String msg = "";  
  102.         try {  
  103.             // 向服务器利用Socket发送信息  
  104.             socket = new Socket("192.168.0.102"5000);  
  105.             // socket = new Socket("127.0.0.1",5000);  
  106.             PrintWriter output = new PrintWriter(socket.getOutputStream());  
  107.   
  108.             output.write(message.toString());  
  109.             output.flush();  
  110.   
  111.             // 这里是接收到Server的信息  
  112.             DataInputStream input = new DataInputStream(socket.getInputStream());  
  113.             byte[] b = new byte[1024];  
  114.             input.read(b);  
  115.             // Server返回的信息  
  116.             msg = new String(b).trim();  
  117.   
  118.             output.close();  
  119.             input.close();  
  120.             socket.close();  
  121.         } catch (UnknownHostException e) {  
  122.             e.printStackTrace();  
  123.         } catch (IOException e) {  
  124.             e.printStackTrace();  
  125.         }  
  126.     }  
  127. }  

这段参考 
http://blog.fens.me/java-websocket-intro/

ChatClient.java 
ChatServer.java 
EmptyClient.java 
WebSocket.jar 
index.html 
Java代码   收藏代码
  1. index.html  
  2. <!DOCTYPE html>  
  3. <html>  
  4.   <head>  
  5.     <title>WebSocket Chat Client</title>  
  6.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7.   
  8.     <script type="text/javascript" src="prototype.js"></script>  
  9.   
  10.     <script type="text/javascript">  
  11.         document.observe("dom:loaded", function() {  
  12.             function log(text) {  
  13.                 $("log").innerHTML = (new Date).getTime() + ": " + (!Object.isUndefined(text) && text !== null ? text : "null") +"<br>"+ $("log").innerHTML;  
  14.                   
  15.             }  
  16.   
  17.             if (!window.WebSocket) {  
  18.                 alert("FATAL: WebSocket not natively supported. This demo will not work!");  
  19.             }  
  20.   
  21.             var ws;  
  22.   
  23.             $("uriForm").observe("submit", function(e) {  
  24.                 e.stop();  
  25.                 ws = new WebSocket($F("uri"));  
  26.                 ws.onopen = function() {  
  27.                     log("[WebSocket#onopen]");  
  28.                 }  
  29.                 ws.onmessage = function(e) {  
  30.                     log("<b style='color:red;'>[WebSocket#onmessage] 接收消息:" + e.data + "</b>");  
  31.                 }  
  32.                 ws.onclose = function() {  
  33.                     log("[WebSocket#onclose]");  
  34.                     $("uri""connect").invoke("enable");  
  35.                     $("disconnect").disable();  
  36.                     ws = null;  
  37.                 }  
  38.                 $("uri""connect").invoke("disable");  
  39.                 $("disconnect").enable();  
  40.             });  
  41.               
  42.             $("sendForm").observe("submit", function(e) {  
  43.                 e.stop();  
  44.                 if (ws) {  
  45.                     var textField = $("textField");  
  46.                     ws.send(textField.value);  
  47.                     //log("[WebSocket#send] 发送消息:" + textField.value );  
  48.                     textField.value = "";  
  49.                     textField.focus();  
  50.                 }  
  51.             });  
  52.               
  53.             $("clear").observe("click", function(e) {  
  54.                 $("log").innerHTML ='';  
  55.             });  
  56.   
  57.             $("disconnect").observe("click", function(e) {  
  58.                 e.stop();  
  59.                 if (ws) {  
  60.                     ws.close();  
  61.                     ws = null;  
  62.                 }  
  63.             });  
  64.         });  
  65.     </script>  
  66.   </head>  
  67.   <body>  
  68.       <form id="uriForm"><input type="text" id="uri" value="ws://localhost:8887" style="width:200px;"> <input type="submit" id="connect" value="Connect"><input type="button" id="disconnect" value="Disconnect" disabled="disabled"></form><br>  
  69.       <form id="sendForm"><input type="text" id="textField" value="" style="width:200px;"> <input type="submit" value="Send"> <input type="button" id='clear' value="clear msg"></form><br>  
  70.       <form><div id="log" style="width:800px;heigth:450px" ></div></form><br>  
  71.   </body>  
  72. </html>  


EmptyClient.java 
Java代码   收藏代码
  1. import java.net.URI;  
  2.   
  3. import org.java_websocket.WebSocketClient;  
  4. import org.java_websocket.drafts.Draft;  
  5. import org.java_websocket.handshake.ServerHandshake;  
  6.   
  7. public class EmptyClient extends WebSocketClient {  
  8.   
  9.     public EmptyClient( URI serverUri , Draft draft ) {  
  10.         super( serverUri, draft );  
  11.     }  
  12.   
  13.     public EmptyClient( URI serverURI ) {  
  14.         super( serverURI );  
  15.     }  
  16.   
  17.     @Override  
  18.     public void onOpen( ServerHandshake handshakedata ) {  
  19.     }  
  20.   
  21.     @Override  
  22.     public void onMessage( String message ) {  
  23.     }  
  24.   
  25.     @Override  
  26.     public void onClose( int code, String reason, boolean remote ) {  
  27.     }  
  28.   
  29.     @Override  
  30.     public void onError( Exception ex ) {  
  31.     }  
  32.   
  33. }  

ChatServer.java 
Java代码   收藏代码
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4. import java.net.InetAddress;  
  5. import java.net.InetSocketAddress;  
  6. import java.net.UnknownHostException;  
  7. import java.util.Set;  
  8.   
  9. import org.java_websocket.WebSocket;  
  10. import org.java_websocket.WebSocketServer;  
  11. import org.java_websocket.handshake.ClientHandshake;  
  12.   
  13. public class ChatServer extends WebSocketServer {  
  14.   
  15.     public ChatServer( int port ) throws UnknownHostException {  
  16.         supernew InetSocketAddress( InetAddress.getByName( "localhost" ), port ) );  
  17.     }  
  18.   
  19.     public ChatServer( InetSocketAddress address ) {  
  20.         super( address );  
  21.     }  
  22.   
  23.     @Override  
  24.     public void onOpen( WebSocket conn, ClientHandshake handshake ) {  
  25.         try {  
  26.             this.sendToAll( "new" );  
  27.         } catch ( InterruptedException ex ) {  
  28.             ex.printStackTrace();  
  29.         }  
  30.         System.out.println( conn + " entered the room!" );  
  31.     }  
  32.   
  33.     @Override  
  34.     public void onClose( WebSocket conn, int code, String reason, boolean remote ) {  
  35.         try {  
  36.             this.sendToAll( conn + " has left the room!" );  
  37.         } catch ( InterruptedException ex ) {  
  38.             ex.printStackTrace();  
  39.         }  
  40.         System.out.println( conn + " has left the room!" );  
  41.     }  
  42.   
  43.     @Override  
  44.     public void onMessage( WebSocket conn, String message ) {  
  45.         try {  
  46.             this.sendToAll( message );  
  47.         } catch ( InterruptedException ex ) {  
  48.             ex.printStackTrace();  
  49.         }  
  50.         System.out.println( conn + ": " + message );  
  51.     }  
  52.   
  53.   
  54.     @Override  
  55.     public void onError( WebSocket conn, Exception ex ) {  
  56.         ex.printStackTrace();  
  57.     }  
  58.   
  59.     public void sendToAll( String text ) throws InterruptedException {  
  60.         Set<WebSocket> con = connections();  
  61.         synchronized ( con ) {  
  62.             for( WebSocket c : con ) {  
  63.                 c.send( text );  
  64.             }  
  65.         }  
  66.     }  
  67.       
  68.     ///  
  69.     public static void main( String[] args ) throws InterruptedException , IOException {  
  70.         //连接部份  
  71.         WebSocket.DEBUG = true;  
  72.         int port = 8887;  
  73.         try {  
  74.             port = Integer.parseInt( args[ 0 ] );  
  75.         } catch ( Exception ex ) { }  
  76.         ChatServer s = new ChatServer( port );  
  77.         s.start();  
  78.         System.out.println( "ChatServer started on port: " + s.getPort() );  
  79.   
  80.         //服务端 发送消息处理部份  
  81.         BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) );  
  82.         while ( true ) {  
  83.             String in = sysin.readLine();  
  84.             s.sendToAll( in );  
  85.         }  
  86.     }  
  87.   
  88. }  


Java代码   收藏代码
  1. import java.awt.Container;  
  2. import java.awt.GridLayout;  
  3. import java.awt.event.ActionEvent;  
  4. import java.awt.event.ActionListener;  
  5. import java.awt.event.WindowEvent;  
  6. import java.net.URI;  
  7. import java.net.URISyntaxException;  
  8.   
  9. import javax.swing.JButton;  
  10. import javax.swing.JComboBox;  
  11. import javax.swing.JFrame;  
  12. import javax.swing.JScrollPane;  
  13. import javax.swing.JTextArea;  
  14. import javax.swing.JTextField;  
  15.   
  16. import org.java_websocket.WebSocket;  
  17. import org.java_websocket.WebSocketClient;  
  18. import org.java_websocket.drafts.Draft;  
  19. import org.java_websocket.drafts.Draft_10;  
  20. import org.java_websocket.drafts.Draft_17;  
  21. import org.java_websocket.drafts.Draft_75;  
  22. import org.java_websocket.drafts.Draft_76;  
  23. import org.java_websocket.handshake.ServerHandshake;  
  24.   
  25. public class ChatClient extends JFrame implements ActionListener {  
  26.     private static final long serialVersionUID = -6056260699202978657L;  
  27.   
  28.     private final JTextField uriField;  
  29.     private final JButton connect;  
  30.     private final JButton close;  
  31.     private final JTextArea ta;  
  32.     private final JTextField chatField;  
  33.     private final JComboBox draft;  
  34.     private WebSocketClient cc;  
  35.   
  36.     public ChatClient( String defaultlocation ) {  
  37.         super"WebSocket Chat Client" );  
  38.         Container c = getContentPane();  
  39.         GridLayout layout = new GridLayout();  
  40.         layout.setColumns( 1 );  
  41.         layout.setRows( 6 );  
  42.         c.setLayout( layout );  
  43.   
  44.         Draft[] drafts = { new Draft_17(), new Draft_10(), new Draft_76(), new Draft_75() };  
  45.         draft = new JComboBox( drafts );  
  46.         c.add( draft );  
  47.   
  48.         uriField = new JTextField();  
  49.         uriField.setText( defaultlocation );  
  50.         c.add( uriField );  
  51.   
  52.         connect = new JButton( "Connect" );  
  53.         connect.addActionListener( this );  
  54.         c.add( connect );  
  55.   
  56.         close = new JButton( "Close" );  
  57.         close.addActionListener( this );  
  58.         close.setEnabled( false );  
  59.         c.add( close );  
  60.   
  61.         JScrollPane scroll = new JScrollPane();  
  62.         ta = new JTextArea();  
  63.         scroll.setViewportView( ta );  
  64.         c.add( scroll );  
  65.   
  66.         chatField = new JTextField();  
  67.         chatField.setText( "" );  
  68.         chatField.addActionListener( this );  
  69.         c.add( chatField );  
  70.   
  71.         java.awt.Dimension d = new java.awt.Dimension( 300400 );  
  72.         setPreferredSize( d );  
  73.         setSize( d );  
  74.   
  75.         addWindowListener( new java.awt.event.WindowAdapter() {  
  76.             @Override  
  77.             public void windowClosing( WindowEvent e ) {  
  78.                 if( cc != null ) {  
  79.                     cc.close();  
  80.                 }  
  81.                 dispose();  
  82.             }  
  83.         } );  
  84.   
  85.         setLocationRelativeTo( null );  
  86.         setVisible( true );  
  87.     }  
  88.   
  89.     public void actionPerformed( ActionEvent e ) {  
  90.   
  91.         if( e.getSource() == chatField ) {  
  92.             if( cc != null ) {  
  93.                 try {  
  94.                     cc.send( chatField.getText() );  
  95.                     chatField.setText( "" );  
  96.                     chatField.requestFocus();  
  97.                 } catch ( InterruptedException ex ) {  
  98.                     ex.printStackTrace();  
  99.                 }  
  100.             }  
  101.   
  102.         } else if( e.getSource() == connect ) {  
  103.             try {  
  104.                 // cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() );  
  105.                 cc = new WebSocketClient( new URI( uriField.getText() ), (Draft) draft.getSelectedItem() ) {  
  106.   
  107.                     @Override  
  108.                     public void onMessage( String message ) {  
  109.                         ta.append( "got: " + message + "\n" );  
  110.                         ta.setCaretPosition( ta.getDocument().getLength() );  
  111.                     }  
  112.   
  113.                     @Override  
  114.                     public void onOpen( ServerHandshake handshake ) {  
  115.                         ta.append( "You are connected to ChatServer: " + getURI() + "\n" );  
  116.                         ta.setCaretPosition( ta.getDocument().getLength() );  
  117.                     }  
  118.   
  119.                     @Override  
  120.                     public void onClose( int code, String reason, boolean remote ) {  
  121.                         ta.append( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n" );  
  122.                         ta.setCaretPosition( ta.getDocument().getLength() );  
  123.                         connect.setEnabled( true );  
  124.                         uriField.setEditable( true );  
  125.                         draft.setEditable( true );  
  126.                         close.setEnabled( false );  
  127.                     }  
  128.   
  129.                     @Override  
  130.                     public void onError( Exception ex ) {  
  131.                         ta.append( "Exception occured ...\n" + ex + "\n" );  
  132.                         ta.setCaretPosition( ta.getDocument().getLength() );  
  133.                         ex.printStackTrace();  
  134.                         connect.setEnabled( true );  
  135.                         uriField.setEditable( true );  
  136.                         draft.setEditable( true );  
  137.                         close.setEnabled( false );  
  138.                     }  
  139.                 };  
  140.   
  141.                 close.setEnabled( true );  
  142.                 connect.setEnabled( false );  
  143.                 uriField.setEditable( false );  
  144.                 draft.setEditable( false );  
  145.                 cc.connect();  
  146.             } catch ( URISyntaxException ex ) {  
  147.                 ta.append( uriField.getText() + " is not a valid WebSocket URI\n" );  
  148.             }  
  149.         } else if( e.getSource() == close ) {  
  150.             try {  
  151.                 cc.close();  
  152.             } catch ( Exception ex ) {  
  153.                 ex.printStackTrace();  
  154.             }  
  155.         }  
  156.     }  
  157.   
  158.     public static void main( String[] args ) {  
  159.         WebSocket.DEBUG = true;  
  160.         String location;  
  161.         if( args.length != 0 ) {  
  162.             location = args[ 0 ];  
  163.             System.out.println( "Default server url specified: \'" + location + "\'" );  
  164.         } else {  
  165.             location = "ws://localhost:8887";  
  166.             System.out.println( "Default server url not specified: defaulting to \'" + location + "\'" );  
  167.         }  
  168.         new ChatClient( location );  
  169.     }  
  170.   
  171. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值