websocket-demo

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. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值