Knowledge Point :websocket get native IP&websocket front-end message push
practical issues to solve :
When the front-end user logs on, the same account password is allowed to log on only one IP;
The same IP allows only one account password to be logged in.
Main realization Idea:
1. Front-end websocket push messages , create a new websocket, pass some of the front-end parameters to the background
Sendmsg ()//Send data
2. The front and back end establishes the connection trigger, the client can connect to the WebSocket server side through this URL, when the connection succeeds, calls its own OnOpen method
The backend adds the session parameter, which sends the data to the client.
3. When there is an exception or error, there is a corresponding error exception handling mechanism at the front and back end.
Back-end onerror () Processing: Error.printstacktrace ();
Front-end onerror Processing: Websocket.close ();
4. monitoring window shutdown Events
When the window is closed, the active to close the WebSocket connection, to prevent the connection is not disconnected before closing the window, server side will throw an exception.
Window.onbeforeunload = function () {
Websocket.close ();
}
Related Code implementation
Front-end JS
WebSocket Push Message
Localip by invoking the interface query, given later, this is the native IP
Sendwebsocketmsg ();
function Sendwebsocketmsg () {
Determine if the current browser supports WebSocket
var test = Window.location.host;
var tstr = UserName + "," +localip
if (' WebSocket ' in window) {
This parameter only allows strings and does not support JSON
WebSocket = new WebSocket (Getrootpath (). Replace ("http", "ws") + "/websocket/" +tstr);
}
callback method where the connection error occurred
Websocket.onerror = function () {
Websocket.close ();
};
callback method for successful connection establishment
Websocket.onopen = function () {
/*
SetInterval (function () {
Websocket.send (UserName);
}, 10000);
*/
}
Listen to the window Shutdown event, when the window is closed, actively to close the WebSocket connection, to prevent the connection has not been disconnected and close the window, the server side will throw an exception.
Window.onbeforeunload = function () {
Websocket.close ();
}
callback method to receive the message
Websocket.onmessage = function (event) {
}
callback method for connection shutdown
Websocket.onclose = function () {
Websocket.close ();
}
}
Java implementation
@ServerEndpoint ("/websocket/{tstr}")
public class Websocketforjsp {
A static variable that is used to record the current number of online connections. It should be designed to be thread-safe.
private static int onlinecount = 0;
The thread-safe set of the concurrent package that holds the corresponding Mywebsocket object for each client. To enable the server to communicate with a single client, you can use a map to store it, where key can identify the user
public static copyonwritearrayset<websocketforjsp> Websocketset = new copyonwritearrayset<websocketforjsp > ();
//A connection session with a client, which is required to send data to the client
Private session session;
//login user name
public String userName;
//Owned IP
Pub LIC String IP;
/**
* Connection established method for successful invocation
* @param session Optional parameters. Session is a connection to a client, it is necessary to send data to the client
*/
@OnOpen
public void OnOpen (@PathParam ("Tstr") String Tstr, session session) {
string[] str = tstr.split (",");
This.username = str[0];
This.ip = str[1];
This.session = session;
Websocketset.add (this);//Join Set in
Addonlinecount ();//online number plus 1
System.out.println ("New connection Added! The current number of online people is "+ getonlinecount ());
}
//public void OnOpen (@PathParam ("name") String name, session session) {
//this.username = name;
This.session = session;
//Websocketset.add (this);//Join Set in
//Addonlinecount ();//online number plus 1
//SYSTEM.OUT.PRINTLN ("New connection added!") The current number of online people is "+ getonlinecount ());
//}
/**
* Method of Connection Close call
*/
@OnClose
public void OnClose () {
Websocketset.remove (this); Remove from set
Subonlinecount (); Online number minus 1
System.out.println ("There's a connection off!") The current number of online people is "+ getonlinecount ());
}
/**
* Method called after receiving a client message
* @param message client sends messages over
* @param session Optional Parameters
*/
@OnMessage
public void OnMessage (String message, session session) {
SYSTEM.OUT.PRINTLN ("Message from client:" + message);
/*
userName = message;
for (websocketforjsp Item:websocketset) {
try {
Item.sendmessage (message);
} catch (IOException e) {
E.printstacktrace ();
Continue
}
}
*/
}
/**
* Called when an error occurs
* @param session
* @param error
*/
@OnError
public void OnError (session session, throwable error) {
SYSTEM.OUT.PRINTLN ("error occurred");
Error.printstacktrace ();
}
/**
* This method is not the same as the above methods. Without annotations, it is based on the method you need to add.
* @param message
* @throws IOException
*/
public void SendMessage (String message) throws ioexception{
This.session.getBasicRemote (). SendText (message);
This.session.getAsyncRemote (). SendText (message);
}
public static synchronized int Getonlinecount () {
return onlinecount;
}
public static synchronized void Addonlinecount () {
websocketforjsp.onlinecount++;
}
public static synchronized void Subonlinecount () {
websocketforjsp.onlinecount--;
}
}
Packages that support javax need to be introduced
. xml
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
About getting a native IP
Need to call an interface, the request with the past call the following method can be implemented, this interface casually, as long as the AJAX call can be
@RequestMapping (value= "GetIP")
@ResponseBody
Public String GetIP (HttpServletRequest request) {
User UserInfo = (user) request.getsession (). getattribute ("user");
String IP = userinfo.getipaddr ();
return IP;
}
Use WebSocket to monitor whether to exit abnormally or to close the login window unexpectedly