This article is a shared experience of the recent use of websocket.
First of all, what is WebSocket, interested friends can look here: Http://zh.wikipedia.org/zh-cn/WebSocket
With a basic understanding of websocket, we can start developing websocket applications and recommend using MAVEN to build projects. The server I'm using is Tomcat 7.0.56 (Tomcat 7 or later to use WebSocket, and at least 7.0.47 or later is supported, LZ started with 7.0.41 deployment did not succeed ...).WebSocket also requires javaee7 support, so you need to refer to the jar in Pom.xml:
<span style= "White-space:pre" ></span><dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </ dependency> <dependency> <groupId>javax.websocket</groupId> <artifactid >javax.websocket-api</artifactId> <version>1.0</version> <scope>provided </scope> </dependency> <!--add Fastjson-1.1.34.jar-- <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version >1.1.34</version> </dependency>
because Tomcat comes with WEBSOCKET-API, the projectWebsocket-api is provided, easy to compile. You can then write the server-side websocket program, sample code:
Package Com.jiepu.visuallab.web.servlet;import Com.alibaba.fastjson.json;import com.jiepu.visuallab.common.c; Import Com.jiepu.visuallab.common.bean.socketreply;import Com.jiepu.visuallab.common.tools.hosttools;import Javax.websocket.*;import Javax.websocket.server.serverendpoint;import Java.util.hashmap;import Java.util.Map; Import java.util.set;/** * * Created by ZENGXM on 2014/11/4. */@ServerEndpoint ("/websocket/test") public class Hostwebsocketservlet {private static map<string, session> Sess ions = new hashmap<string, session> (); Public Hostwebsocketservlet () {System.out.println ("--------------------------------------"); /** * Bulk Message to Client * @param category * @param data */public synchronized static void Sendall (String c Ategory, Object data) {socketreply re = new socketreply (category, data); String replystr = json.tojsonstring (re); System.out.println ("Start mass message! "); set<string> keys = Sessions.keyset (); for (String K:keys) {Session s = sessions.get (k); if (S.isopen ()) {try{s.getbasicremote (). SendText (REPLYSTR); SYSTEM.OUT.PRINTLN ("Sent successfully, id=" +k); }catch (Exception e) {System.err.println ("Send error:" +e.getmessage ()); }}}} @OnMessage public void OnMessage (Session session, String msg) {System.out.printl N ("received information"); try {session.getbasicremote (). SendText ("get"); }catch (Exception e) {e.printstacktrace (); }} @OnOpen public void OnOpen (session session, Endpointconfig Config) {try {sessions.put (sess Ion.getid (), session); socketreply re = new socketreply (C.host_data, Hosttools.gethostlist ()); String replystr = json.tojsonstring (re); Session.getbasicremote (). SendText (REPLYSTR); }catch (Exception e) {e.printstacktrace (); }} @OnError public void OnError (Session session, Throwable Throwable) {} @OnClose public void OnClose (S Ession session, Closereason reason) {try {System.out.println ("Disconnected, id=" +session.getid ()); Synchronized (sessions) {Sessions.remove (Session.getid ()); }}catch (Exception e) {e.printstacktrace (); } }}
In the HTML page, you can connect to the WebSocket defined above:
var url = "ws://" +document.location.host+ "${base}/websocket/test"; var ws = new WebSocket (URL); Ws.onopen = function (e) { console.log ("WS connect success!"); Hostutil.start (); Hostconsole.init (); Listeners.push (Hostconsole); } Ws.onmessage = function (evt) { console.log ("ws Get:" +evt.data);
The ${base} in the code above is the project name, which is replaced with the actual path. Deploy the project to Tomcat, run it, and the console can see the connection information:
Summary: 1. If the environment is set up, the operation of the project did not error, but can not connect websocket (JS side reported 404 error), it is possible to see if the jar conflict. Is the project Lib inside is not have WEBSOCKET-API related jar, some words to delete, otherwise will with Tomcat comes with websocket conflict, cause the service end program did not execute.
More WebSocket learning materials in this: http://mgreau.com/posts/2013/11/11/javaee7-websocket-angularjs-wildfly.html
Using WebSocket in a Java EE project