Java front and back end implementation WebSocket message push (targeted push)
1, need to add a dependency package, in the Pom.xml file to add
<dependency>
<groupId>javax</groupId>
<artifactid>javaee-api</artifactid >
<version>7.0</version>
<scope>provided</scope>
</dependency>
2. Client code
Here I am in order to make HttpSession login is the same, so I made two pages, a login jump page, a link to websocket receive messages
A. Login page
<! DOCTYPE html>
B. Receiving a message push page
<! DOCTYPE html>
3, on the back-end code here for 4 documents
A general-purpose msg file, a httpsession for getting the current session, a listener with no httpsession (no creation), a link for websocket and a message to send
A. Common msg file
Package com.boli.srcoin.websocket;
Import Java.util.Date; /** * @author:admin</br> * @DESC: <p>websocket message Model </p></br>/* public class MSG {//push
Human ID private String fromuid;
Fixed-point push Person ID private String touid;
FIXED-POINT push unit ID private String toorgid;
Message body private String data;
Push time Private Date createdate = new Date ();
Message status private Integer flag; Public msg () {} public msg (string fromuid, String touid, String toorgid, string data, Date CreateDate, Integer
Flag) {this.fromuid = Fromuid;
This.touid = Touid;
This.toorgid = Toorgid;
This.data = data;
This.createdate = CreateDate;
This.flag = Flag;
Public String Getfromuid () {return fromuid;
} public void Setfromuid (String fromuid) {this.fromuid = Fromuid;
Public String Gettouid () {return touid; } public void Settouid (String TouiD) {this.touid = Touid;
Public String Gettoorgid () {return toorgid;
} public void Settoorgid (String toorgid) {this.toorgid = Toorgid;
Public String GetData () {return data;
public void SetData (String data) {this.data = data;
Public Date Getcreatedate () {return createdate;
The public void Setcreatedate (Date createdate) {this.createdate = CreateDate;
Public Integer Getflag () {return flag;
The public void Setflag (Integer flag) {This.flag = flag;
@Override public String toString () {return "msg{" + "fromuid= '" + fromuid + ' \ "+ ", touid= '" + touid + ' + ", toorgid= '" + toorgid + ' \ ' + ", data= '" + da
Ta + ' \ ' + ', createdate= "+ CreateDate +", flag= "+ Flag + '}"; }
}
B. Used in WebSocket or to HttpSession
Package com.boli.srcoin.websocket;
Import javax.servlet.http.HttpSession;
Import Javax.websocket.HandshakeResponse;
Import Javax.websocket.server.HandshakeRequest;
Import Javax.websocket.server.ServerEndpointConfig;
Import Javax.websocket.server.ServerEndpointConfig.Configurator;
/**
* @author:admin</br>
* @DESC: <p> speak http request session in WebSocket session </p></ Br>
*/Public
class Httpsessionconfigurator extends Configurator {
@Override public
Void Modifyhandshake (serverendpointconfig sec,
handshakerequest request, handshakeresponse response) {
// Gets the session
HttpSession HttpSession = (HttpSession) of the current HTTP connection request.gethttpsession ();
Injects HTTP session information into WebSocket session
Sec.getuserproperties (). Put (HttpSession.class.getName (), HttpSession);
}
C. For monitoring there is no httpsession, did not create
Package com.boli.srcoin.websocket;
Import javax.servlet.ServletRequestEvent;
Import Javax.servlet.ServletRequestListener;
Import Javax.servlet.annotation.WebListener;
Import Javax.servlet.http.HttpServletRequest;
@WebListener public
class Requestlistener implements Servletrequestlistener {public
void requestinitialized ( Servletrequestevent SRE) {
//Bring all request requests to httpsession
(httpservletrequest) sre.getservletrequest ()). GetSession ();
The public Requestlistener () {
//TODO auto-generated constructor stub} is public
void requestdestroyed ( Servletrequestevent arg0) {
//TODO auto-generated method stub
}
}
D. Receiving WebSocket links and sending messages
Package com.boli.srcoin.websocket;
Import Com.alibaba.fastjson.JSON;
Import Org.apache.commons.lang.StringUtils;
Import Org.apache.log4j.Logger;
Import javax.servlet.http.HttpSession;
Import javax.websocket.*;
Import Javax.websocket.server.ServerEndpoint;
Import java.io.IOException;
Import Java.util.concurrent.ConcurrentHashMap;
Import Java.util.concurrent.ConcurrentMap; /** * @author:admin</br> * @DESC: <p> Note {@link serverendpoint} declare websocket server </p></br>/@Se Rverendpoint (value = "/chat", configurator = httpsessionconfigurator.class) public class WSServer {static Private Lo
Gger logger = Logger.getlogger (Wsserver.class);
Online number thread safety private static int onlinecount = 0; Connection collection UserId => server key value to thread safe static public final concurrentmap<string, wsserver> map = new Concurrenthas
Hmap<> ();
A connection session with a client, which needs to be sent to the client to send the data private sessions;
The current session HttpSession private HttpSession HttpSession; /** * @param session websocket Connection Sesson * @param config {@link Com.github.websocket.configuration.HttpSessionC Onfigurator} * @DESC <p> annotations {@link OnOpen} declares a method for client connection entry </p>/@OnOpen public void OnOpen (sess Ion session, Endpointconfig Config) {//get httpSession this.httpsession = (httpSession) config.getuserpro
Perties (). Get (HttpSession.class.getName ()); Gets the Session object Sobject (this is the saved session object after the Java Web login, where the user information, contains the UserID) String user = (String) this.httpSession.get
Attribute ("user");
This.session = session;
System.out.println (user+ "-------" +this.session.getid ());
Can only have one link if (map.get (user)!=null) {//Remove connection Map.Remove (user) for a user;
Number of connections-1 subonlinecount ();
///will connect the Session object to map Map.put (user, this);
Connection number +1 addonlinecount ();
Logger.info ("There is a new connection, the current number of connections is:" + getonlinecount ());
}
/** * <p>{@link OnClose} close connection </p>/* @OnClose public void OnClose () {/** * Get current connection information {@code Commonconstant.user_login_session} for HTTP Session name * */String USER = (string) thi
S.httpsession.getattribute ("user");
Remove connection map.remove (user);
Number of connections-1 subonlinecount ();
Logger.info ("There is a connection disconnect, the current number of connections is:" + getonlinecount ()); /** * <p>{@link OnMessage} Message Listener processing method </p> * * @param messages Message Object {@link Com.github.websock ET.MSG.MSG} 's JSON object * @throws IOException Exception */@OnMessage public void OnMessage (String message) throws I
oexception {//Message to MSG object msg msg = Json.parseobject (messages, msg.class);
TODO can do something with msg ...//userid WSServer _client = Map.get (Msg.gettouid ()) to obtain a fixed-point sender according to the MSG message object;
fixed-point Send if (Stringutils.isnotempty (Msg.gettouid ())) {if (null!= _client) { Whether the connection is judged if (_client.session.isopen ())//message sent _client.sessi
On.getbasicremote (). SendText (Json.tojsonstring (msg)); }///Mass if (Stringutils.isempty (Msg.gettouid ())) {//mass connected user for (wsse
RVer client:map.values ()) {client.session.getBasicRemote (). SendText (Json.tojsonstring (msg));
/** * <p>{@link OnError} websocket System Exception handling </p> * * @param t Abnormal * *
@OnError public void OnError (Throwable t) {logger.error (t);
T.printstacktrace (); /** * <p> System Proactive This is a static method that can be invoked at other appropriate places and times of the program after the Web is started, which implements the system's active push </p> * * @param msg Message Object {@li
The JSON object of NK COM.GITHUB.WEBSOCKET.MSG.MSG}/static public void Pushbysys (msg msg) {//todo can also implement fixed-point push MSG is transmitted with the need to send a message to who msg.gettouid ()//through the map to get that user's session WSServer Ws=map.Get (Msg.gettouid ());
try {if (ws!=null) {ws.session.getBasicRemote (). SendText ("123456");
} catch (IOException E1) {e1.printstacktrace (); }//Mass/*for (WSServer client:map.values ()) {try {client.session.ge
Tbasicremote (). SendText (Json.tojsonstring (msg));
catch (IOException e) {e.printstacktrace (); }*/}//Get the number of connections private static synchronized int getonlinecount () {return Wsserver.onlinecou
nt
}//Increase the number of connections private static synchronized void Addonlinecount () {wsserver.onlinecount++;
}//Reduce the number of connections private static synchronized void Subonlinecount () {wsserver.onlinecount--; }
}
4, at the back end of the call, that is, login and call to send messages
Package Com.boli.srcoin.member.service.impl;
Import Java.util.HashMap;
Import Java.util.Map;
Import Org.springframework.stereotype.Service;
Import org.springframework.transaction.annotation.Transactional;
Import Com.boli.framework.system.result.StandardResult;
Import Com.boli.framework.utils.WebUtil;
Import Com.boli.srcoin.member.form.MemberLoginForm;
Import Com.boli.srcoin.member.service.LoginMemberService;
Import COM.BOLI.SRCOIN.WEBSOCKET.MSG;
Import Com.boli.srcoin.websocket.WSServer;
@Service public class Loginmemberserviceimpl implements loginmemberservice{@Override @Transactional (readOnly = False) Public Standardresult Tologin (Memberloginform loginform) {webutil.getsession (). setattribute ("User",
Loginform.getuser ());
Map<string,object> map=new hashmap<> ();
Map.put ("SessionId", Webutil.getsession (). GetId ());
Map.put ("User", Loginform.getuser ());
SYSTEM.OUT.PRINTLN ("Invoke Login Method:" +webutil.getsession (). GetId () +loginform.getuser ()); Return Standardresult.OK (map);
@Override @Transactional (readOnly = false) public Standardresult Tishi () {msg msg=new msg ();
Msg.settouid ("PPP");
Wsserver.pushbysys (msg);
return Standardresult.ok ();
}
}
5, the result of the call as shown
SOURCE Link: http://download.csdn.net/download/qq_31151929/10207702