what is websocket.
WebSocket is a real-time technology for resolving server - side and client communication. Ajax can also communicate, but he can't do it in real time. We want real-time effects before websocket, all through polling, which is obviously a waste of resources.
WebSocket's strength is that, compared to Ajax needs to initiate requests from the client, WebSocket's server and client can push messages to each other in real time.
how to use WebSocket.
First you have to have a browser that supports it. (IE is not supported)
After the socket is created, the client can respond to the socket by onopen,onmessage,onclose,onerror these four times.
Give me a chestnut:
Environment: TOMCAT7 or above. Jdk7 or above
1.websockettest.java
Package instance;
Import java.io.IOException;
Import Javax.websocket.OnClose;
Import Javax.websocket.OnMessage;
Import Javax.websocket.OnOpen;
Import javax.websocket.Session;
Import Javax.websocket.server.ServerEndpoint; <span style= "color: #ff6666;" > @ServerEndpoint ("/websocket") </span> public class Websockettest {@OnMessage public void OnMessage (String message, session sessions) throws IOException, interruptedexception {//Print the client message for testing p
Urposes System.out.println ("Received:" + message);
Send the "the" to "the" Client Session.getbasicremote (). SendText ("This is the The");
Send 3 messages to the client every 5 seconds int sentmessages = 0;
while (Sentmessages < 3) {Thread.Sleep (5000);
Session.getbasicremote (). SendText ("This is a intermediate server message.")
Count: "+ sentmessages);
sentmessages++; }//Send a final mesSage to the client Session.getbasicremote (). SendText ("This is the last Server message");
@OnOpen public void OnOpen () {System.out.println ("Client connected");
@OnClose public void OnClose () {System.out.println ("Connection closed");
}
}
2.page.html
<! DOCTYPE html>
Here to note:
var webSocket =
new WebSocket (' Ws://localhost:8080/webscoket/websocket ');
Where: One is the project name, one is the server name of the annotation
Here you start the server, run page.html
As shown in the picture, it means success.