Java Implementation WebSocket Ultimate guide

Source: Internet
Author: User
Tags sendmsg

1. Add Dependency in Pom

<dependency>            <groupId>org.springframework</groupId>            <artifactId> spring-websocket</artifactid>            <version>${spring-version}</version>        </dependency >                <dependency>            <groupId>org.springframework</groupId>            <artifactId> spring-messaging</artifactid>            <version>${spring-version}</version>        </dependency >

2. Add WebSocket interception in Spring-mvc.xml

<websocket:handlers allowed-origins= "*" >        <websocket:mapping path= "/ws" handler= "MyHandler"/>        <websocket:handshake-interceptors>            <bean class= "Com.cloudunicomm.interceptor.HandshakeInterceptor" />        </websocket:handshake-interceptors>    </websocket:handlers>    <bean id= "MyHandler" class= "Com.cloudunicomm.interceptor.MySocketHandler"/>

3. Add Mysockethandler Class

Package Com.cloudunicomm.interceptor;import Java.io.ioexception;import Java.util.hashmap;import java.util.Iterator ; Import Java.util.map;import Java.util.map.entry;import Java.util.set;import Java.util.concurrent.copyonwritearrayset;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.data.redis.core.listoperations;import org.springframework.data.redis.core.RedisTemplate; Import Org.springframework.web.socket.closestatus;import Org.springframework.web.socket.textmessage;import Org.springframework.web.socket.websocketmessage;import Org.springframework.web.socket.websocketsession;import Org.springframework.web.socket.handler.textwebsockethandler;import Com.alibaba.fastjson.jsonobject;import   Com.cloudunicomm.vo.User; public class Mysockethandler extends Textwebsockethandler {private static final Logger Logger = Loggerfactory.getlogg    ER (mysockethandler.class); Number of people on line private static int COunt;     private static copyonwritearrayset<websocketsession> set = new copyonwritearrayset<> ();    public static map<string,websocketsession> SessionID = new hashmap<string,websocketsession> ();          Private Websocketsession session;            @Autowiredprivate redistemplate<string,string> redistemplate; @Override public void Afterconnectionestablished (websocketsession session) {map<string, object> Map = ses    Sion.getattributes ();    String UserID = map.get ("userid"). toString ();       Sessionid.put (userid, session);         This.session = session;         try{Set.add (this.session);         }catch (Exception e) {e.printstacktrace ();         } mysockethandler.addonlinecount ();      System.out.println ("Current number of connections:" + getonlinecount ()); } public void afterconnectionclosed (websocketsession session,closestatus closestatus) {this.session = Sessio       N String UserID = session.getattributes (). Get ("userid"). toString ();       Redistemplate.delete ("Seat_" +userid);       Session.getattributes (). Remove ("userid");         Set.remove (this.session);         Subonlinecount ();      System.out.println ("Current number of connections:" + getonlinecount ()); } public void Handlemessage (Websocketsession session,websocketmessage<?>message) {System.out.print        ln ("From client message:" +message.getpayload () + "_" + Session.getid ());            Send to everyone/* for (websocketsession Ssion:set) {try {ssion.sendmessage (message);             }catch (IOException e) {e.printstacktrace ();           }} *//Parse message Modify User state try{//id:state,//username:sip:[email protected]:9060       string[] state = Message.getpayload (). toString (). Split ("_");       listoperations<string,string> value = Redistemplate.opsforlist ();       String val = value.rightpop ("Seat_" +state[0]). toString (); User user = (user) Jsonobject.tojaVaobject (Jsonobject.parseobject (Val), User.class);       User.setstate (Integer.parseint (state[1));       The actual is to parse out now first write dead User.setnext_hop ("123.57.144.26:9060/udp");       User.setto ("<sip:[email protected]:9060>");       String struser = jsonobject.tojsonstring (user);       Value.leftpush ("Seat_" +user.getid (). toString (), struser);       }catch (Exception e) {logger.error (E.getmessage (), E);      }} public static int Getonlinecount () {return count;      } public static void Addonlinecount () {count++;      } public static void Subonlinecount () {count--;  /** * Give the specified connection push message * @param session * @param message * */public string pushmsg (string SessionID, String message) {for (websocketsession Ssion:set) {try {if (Sessionid.equals (ssion                    . GetId ())) {Ssion.sendmessage (new TextMessage (message)); Return "machine:" + SEssionid+ "Push Success";             }}catch (IOException e) {e.printstacktrace ();      }} Return "Push failed";          /** * to all connections * @param message * @return */public string pushmsg (String message) {          int i = 0;                 for (Websocketsession Ssion:set) {try {ssion.sendmessage (new TextMessage (message));             i++;             }catch (IOException e) {e.printstacktrace ();         }} return "Total" + i + "get Push";   }}

4. Add Handshakeinterceptor Class

 

Package Com.cloudunicomm.interceptor;import Java.util.map;import Javax.servlet.http.httpsession;import Org.springframework.http.server.serverhttprequest;import Org.springframework.http.server.ServerHttpResponse; Import Org.springframework.http.server.servletserverhttprequest;import Org.springframework.web.socket.websockethandler;import   Org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; public class Handshakeinterceptor extends Httpsessionhandshakeinterceptor {/* * handshake pre-processing action */@Overrid             E public boolean beforehandshake (ServerHTTPRequest request, serverhttpresponse response, Websockethandler handler,               Map<string,object> map) throws Exception {System.out.println ("front handshake"); if (Request instanceof Servletserverhttprequest) {servletserverhttprequest ServletRequest = (servletserverhttprequest           ) Request;          HttpSession HttpSession = Servletrequest.getservletrequest (). GetSession (True);if (null! = httpSession) {//String UserID = Httpsession.getattribute ("userid"). toString ();             String UserID = Httpsession.getattribute ("userid"). toString ();          Map.put ("userid", UserID);      }} return Super.beforehandshake (request, response, handler, map); } @Override public void Afterhandshake (ServerHTTPRequest request,serverhttpresponse Response,websockethandl      ER wshandler,exception ex) {Super.afterhandshake (Request, Response, Wshandler, ex);   }   }

5, add TestController

Package Com.cloudunicomm.controller;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.RequestMapping, @Controller @RequestMapping ("/im") public class      TestController {/* @Bean public mysorkethandle Mysorkethandle () {return new Mysorkethandle ();            } */@RequestMapping ("/page") public String page (httpservletrequest request, httpservletresponse response) {      return "Impage"; }/* @ResponseBody @RequestMapping ("/push") public string push (@RequestParam (required = false) string SE         Ssionid, httpservletresponse response) {String msg= "";             if (Stringutils.isempty (sessionId)) {msg =mysorkethandle (). PUSHMSG ("Server pushes information out");         SYSTEM.OUT.PRINTLN (msg);             }else{msg =mysorkethandle (). Pushmsg (sessionId, "server pushes information out"); System.out.priNTLN (msg);      } return msg;  }  */}

6. Add JSP

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

7. Login Controller

Package Com.cloudunicomm.controller;import Java.util.list;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.lang.stringutils;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.data.redis.core.listoperations;import org.springframework.data.redis.core.RedisTemplate; Import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.CrossOrigin; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestparam;import Org.springframework.web.bind.annotation.responsebody;import Com.alibaba.fastjson.jsonobject;import Com.cloudunicomm.service.userservice;import Com.cloudunicomm.utils.resultmessage;import Com.cloudunicomm.vo.User ; @Controllerpublic class Logincontroller {@Autowiredprivate userservice userservice; @Autowiredprivate redistemplate <String,String> redistemplate; @CrossOrigin (Origins = "*", MAXAGE = +) @RequestMapping ("login") @ResponseBodypublic resultmessage Login (httpservletrequest request, HttpServletResponse response, @RequestParam (name= "username", Required=false) String username, @RequestParam (name= " Password ", required=false) String password) {if (Stringutils.isempty (username) | | Stringutils.isempty (password)) {return Resultmessage.getfail (). Setmessage ("Username password cannot be empty! ");} User user = Userservice.authusernmaandpassword (username,password), if (user = = null) {return Resultmessage.getfail (). Setmessage ("User name password is wrong! ");} String str = redistemplate.opsforlist (). Rightpopandleftpush ("Seat_" +user.getid (), "Seat_" +user.getid ()); if (null! = STR) {return resultmessage.getfail (). Setmessage ("Do not re-login! ");} Login successfully added user to Redis IsLogin modified to online state modified to free user.setislogin (0); user.setstate (0); listoperations<string,string> redislist = Redistemplate.opsforlist (); String struser = jsonobject.tojsonstring (user),//left-to-right deposit stack Redislist.leftpush ("Seat_" +user.getid (). toString (), struser); Request.getsession (). SetAttribute ("UserID ", User.getid ()); return resultmessage.getsuccess (). SetData (User.getid ());}} 

  

 

8. Precautions

1) If the interceptor is to be commented out in the project or the WebSocket link fails

2) If the test is a remote call, the address must be the same

Java Implementation WebSocket Ultimate guide

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.