WebSocket JavaScript API (client)
<script> var URL = "Ws://localhost:8080/websocketchatroom/chatroomserver"; var websocket; var userName; function setconnected (connected) {document.getElementById (' Connect '). disabled=connected; document.getElementById (' disconnect '). Disabled =!connected; document.getElementById (' send '). Disabled =!connected; } function Connect () {if (' WebSocket ' in window) {WebSocket = new WebSocket (URL); }else if (' Mozwebsocket ' in window) {websocket = new Mozwebsocket (URL); }else{alert ("Your browser does not support WebSocket, please replace the latest version of the browser"); Return } Websocket.onopen = function (evnt) {userName = document.getElementById (' userId '). Value; if (UserName = = "") {alert ("User name cannot be null"); Return }else{setconnected (TRUE); Websocket.send (userName + "Join chat room"); } }; Websocket.onmessage = function (evnt) {OnMessage (evnt)}; Websocket.onerror = function (evnt) {onerror (evnt)}; Websocket.onclose = function (evnt) {disconnect (evnt); }} function SendMessage () {var userName = document.getElementById (' userId '). Value; var msg = document.getElementById (' message '). Value; Websocket.send (username+ ":" +msg); } function OnMessage (evnt) {if (typeof Evnt.data = = "string") {log (evnt.data); }} function OnError (evnt) {log (' ERROR: ' + evnt.data); }/*function OnClose (evnt) {setconnected (false); }*/function Disconnect (evnt) {if (websocket! = null) {Websocket.close ($, userName + "exit chat room"); WebSocket = null; Log ("You have exited the chat room"); Setconnected (FALSE); }} function log (message) {var console = document.getElementById (' console '); var p = document.createelement (' P '); P.style.wordwrap = ' Break-word '; P.appendchild (document.createTextNode (message)); Console.appendchild (P); while (Console.childNodes.length >) {console.removechild (console.firstchild); } console.scrolltop = Console.scrollheight; }</script>
- websocket.onopen #当打开一个新的连接时会调用这个方法
- websocket.onmessage #当server有数据返回时调用
- websocket.send () #向服务端发送信息, type includes {string| arraybuffer| arraybufferview| BLOB}
- websocket.close () #向服务器发送关闭的请求, parameter {number} [code] {string} [reason], with related code table, generally use this method to close code 1000, directly close the browser to 1006, Close_abnormal
Status Code |
Name |
Description |
0-999 |
|
Reserved and not used. |
1000 |
Close_normal |
Normal closure; The connection successfully completed whatever purpose for which it was created. |
1001 |
Close_going_away |
The endpoint is going away, either because of a server failure or because the browser are navigating away from the page tha T opened the connection. |
1002 |
Close_protocol_error |
The endpoint is terminating the connection due to a protocol error. |
1003 |
close_unsupported |
The connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only Endpoint received binary data). |
1004 |
|
Reserved. A meaning might is defined in the future. |
1005 |
Close_no_status |
Reserved. Indicates that no status code is provided even though one was expected. |
1006 |
Close_abnormal |
Reserved. Used to indicate this a connection was closed abnormally (that's, with no close frame being sent) when a status code is E Xpected. |
1007 |
|
The endpoint is terminating the connection because a message were received that contained inconsistent data (e.g., non- UTF-8 data within a text message). |
1008 |
|
The endpoint is terminating the connection because it received a message that violates it ' s policy. This was a generic status code, used when codes 1003 and 1009 were not suitable. |
1009 |
Close_too_large |
The endpoint is terminating the connection because a data frame was received this is too large. |
1010 |
|
The client is terminating the connection because it expected the server to negotiate one or more extension, but the server Didn ' t. |
1011 |
|
The server is terminating the connection because it encountered a unexpected condition that prevented it from fulfilling The request. |
1012-1014 |
|
Reserved for future use by the WebSocket standard. |
1015 |
|
Reserved. Indicates that the connection is closed due to a failure to perform a TLS handshake (e.g., the server certificate can ' t b E verified). |
1016-1999 |
|
Reserved for future use by the WebSocket standard. |
2000-2999 |
|
Reserved for use by WebSocket extensions. |
3000-3999 |
|
Available for use by libraries and frameworks. May is used by applications. |
4000-4999 |
|
Available for use by applications. |
WebSocket Java API (Server)
@ServerEndpoint ("/chatroomserver") public class Messageendpoint { private static final arraylist<session> Sessions; static { sessions = new arraylist<session> (); } @OnOpen public void OnOpen (Session session) { Sessions.add (session); } @OnMessage public void OnMessage (String message) { sendMessage (message); } @OnClose public void OnClose (Session Session,closereason Closereason) { sessions.remove (session); SendMessage (Closereason.getreasonphrase ()); } private void SendMessage (String message) {for (Session session:sessions) { try { Session.getbasicremote (). SendText (message); } catch (IOException e) { e.printstacktrace ();}}}}
- @ServerEndpoint ("/chatroomserver"),Serverendpoint converts a Pojo class into WebSocket EndPoint, and the value behind it is the access address
- for annotations please see
Annotation |
Role |
@ServerEndpoint |
Declare a Server Endpoint |
@ClientEndpoint |
Declare a Client Endpoint |
@OnOpen |
Declare This method handles open events |
@OnMessage |
Declare This method handles Websocket messages |
@OnError |
Declare This method handles error |
@OnClose |
Declare This method handles WebSocket close events |
<dependency> <groupId>javax.websocket</groupId> <artifactId> javax.websocket-api</artifactid> <version>1.0</version> <scope>provided</ Scope> </dependency>
I use tomcat,<scope>provided</scope> this sentence must be added, otherwise it will be reported that there are related duplicate classes in 404,tomcat