Use WebSocket and javaeewebsocket in the javaee Project

Source: Internet
Author: User

Use WebSocket and javaeewebsocket in the javaee Project
This article is an example of my recent experience using WebSocket.
First of all, what is WebSocket, interested friends can look here: http://zh.wikipedia.org/zh-cn/WebSocket
After having a basic understanding of WebSocket, we can develop a WebSocket application. We recommend that you use Maven to build a project. The server I use is Tomcat 7.0.56 (WebSocket can be used only in Tomcat 7 or later versions, and at least 7.0.47 or later versions are supported. When LZ starts to use 7.0.41, the deployment fails ...). WebSocket also needs javaee7 support, so you need to reference 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 websocket-api in the project is provided to facilitate compilation. Then you can write the WebSocket program on the server side. The sample code is as follows:
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. * // @ ServerEndpo Int ("/websocket/test") public class HostWebSocketServlet {private static Map <String, Session> sessions = new HashMap <String, Session> (); public HostWebSocketServlet () {System. out. println ("----------------------------------");}/*** send messages to the client * @ param category * @ param data */public synchronized static void sendAll (String category, Object data) {SocketReply re = new SocketReply (category, data ); String replyStr = JSON. toJSONString (re); System. out. println ("start sending group information! "); 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 ("sending error:" + e. getMessage () ;}}}@ OnMessage public void onMessage (Session session, String msg) {System. out. println ("received message"); try {session. getBasicRemote (). sendText ("get");} catch (Exception e) {e. printStackTrace () ;}@ OnOpen public void onOpen (Session session, EndpointConfig config) {try {sessions. put (session. 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 (Session session, CloseReason reason) {try {System. out. println ("disconnected, id =" + session. getId (); synchronized (sessions) {sessions. remove (session. getId () ;}} catch (Exception e) {e. printStackTrace ();}}}



On 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);    }


In the code above, $ {base} is the project name. Replace it with the actual path. Deploy the project to tomcat and run it. The connection information is displayed on the console:

Conclusion: 1. If the environment is set up, no error is reported when running the project, but WebSocket cannot be connected (404 error is reported on the js end). Check whether the jar conflict exists. Is there any jar related to websocket-api in the project lib, if yes, it should be deleted, otherwise it will conflict with the websocket that comes with tomcat, resulting in the server program not being executed.

More websocket learning materials in this: http://mgreau.com/posts/2013/11/11/javaee7-websocket-angularjs-wildfly.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.