1. Add Maven dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> < artifactId > spring - the boot - starter - websocket < / artifactId > < version > 1.3.5. RELEASE < / version > < / dependency >Copy the code
2. The webSocket configuration
/** * webSocket Configuration * @author * @date 2017/10/25. */ @configuration public class WebSocketConfig {/** * Injection ServerEndpointExporter, * This bean will automatically register Websocket endpoint * @return */ @bean public ServerEndpointExporter using the @ServerEndpoint annotation declaration serverEndpointExporter() { return new ServerEndpointExporter(); }}Copy the code
3. Customize the WebSocket
/** * Custom websocket * @author * @date 2017/10/25. */ @serverendpoint (value ="/websocket") @Component public class CustomWebSocket {/** Static variable used to record the number of current online connections. It should be designed to be thread-safe. */ private static int onlineCount = 0; /** A thread-safe Set for the concurrent package, used to hold the corresponding CumWebSocket object for each client. */ private static CopyOnWriteArraySet<CustomWebSocket> webSocketSet = new CopyOnWriteArraySet<CustomWebSocket>(); /** A Session with a client through which to send data to the client */ private Session Session; private static final Loggerlog= LoggerFactory.getLogger(CustomWebSocket.class); Public void OnOpen (session session) {this.session = session; / / to joinsetIn webSocketSet. Add the (this); AddOnlineCount (); log.info("New connection in. Current online population:"+getOnlineCount());
try {
sendMessage("Pretend to have content."); } catch (IOException e) { e.printStackTrace(); }} /** * connect to close the called method */ @onclose public voidonClose() {/ / fromsetRemove webSocketSet. Remove (this); SubOnlineCount (); log.info("Connection closed. Current online population:"+getOnlineCount()); } @param message @param session @onMessage public void OnMessage (String message, Session session) { log.info("Message sent by client:"+message); sendAll(message); } /** * exposed to external groups @param message @throws IOException */ public static void sendInfo(String message) throws IOException { sendAll(message); } /** * @param message */ private static void sendAll(String message) { Arrays.asList(webSocketSet.toArray()).forEach(item -> { CustomWebSocket customWebSocket = (CustomWebSocket) item; / / mass try {customWebSocket. SendMessage (message); } catch (IOException e) { e.printStackTrace(); }}); } @param session @param error @onError public void OnError (session session, Throwable error) { log.info("There's something wrong."); error.printStackTrace(); } /** * reduce the number of online */ private voidsubOnlineCount() { CustomWebSocket.onlineCount--; } /** * Add number of online */ private voidaddOnlineCount() { CustomWebSocket.onlineCount++; } /** * The number of current online * @return
*/
public static synchronized int getOnlineCount() {
returnonlineCount; } /** * Send information * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { / / get the session remotely basic connection send text messages. This session. The getBasicRemote (.) sendText (message); //this.session.getAsyncRemote().sendText(message); }}Copy the code
4. Front-end page
<! DOCTYPE HTML> <html> <head> <title>WebSocket</title> </head> <body> Welcome<br/> <input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript"> var websocket = null; // Check whether the current browser supports WebSocketif('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else{
alert('Not support websocket'} // Connection error callback method websocket.onerror =function() {setMessageInnerHTML("error"); }; // The connection was successfully established with the callback method websocket.onopen =function(event){
setMessageInnerHTML("open"); } // The received message callback method websocket.onMessage =function(event){
setMessageInnerHTML(event.data); } // Connection closure callback method websocket.onclose =function() {setMessageInnerHTML("close"); } // Listen for window closing events, when the window is closed, actively close the Websocket connection, to prevent the connection is not closed, the server will throw exceptions. window.onbeforeunload =function(){ websocket.close(); } // Display the message on the web pagefunction setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>'; } // Close the connectionfunction closeWebSocket(){ websocket.close(); } // Send a messagefunction send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>Copy the code