Websocket, which provides a duplex protocol for communication between client and server (see my book WebSocket), can easily provide the server side of WebSocket using Spring Boot.

The main thing is to make a few notes.

Body code: mysocket.java

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/ws")
@Component
public class CaptureSocket {
    private final static Logger LOGGER = LoggerFactory.getLogger(CaptureSocket.class);

    private static CopyOnWriteArraySet<CaptureSocket> set = new CopyOnWriteArraySet<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) throws IOException,InterruptedException {
        this.session=session;
        set.add(this);
        LOGGER.info("New connection from:" + session.getRequestURI().getHost());
    }

    @OnClose
    public void onClose(a){
        set.remove(this);
        LOGGER.info("Connection closed:" + this.session.getRequestURI().getHost());
    }

    @OnMessage
    public void onMessage(String message,Session session){
        LOGGER.info("Message from client:" + message);
    }

    @OnError
    public void onError(Session session,Throwable err){ LOGGER.info(err.getMessage()); err.printStackTrace(); }}Copy the code

Configuration file: mysocketconfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class CaptureSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(a){
        return newServerEndpointExporter(); }}Copy the code

This configuration file does not need to be displayed, the system will automatically interpret. The “@Configuration” tag probably works.

The purpose of this configuration file, from the point of view of the code, is to accompany the interpretation of the server endpoint. The body mysocket.java has a tag: @serverendpoint (“/ws”)

The corresponding client code is:

var ws;
function wsconnect() {
	var ws = new WebSocket(Ws: / / "192.168.0.98:8085 / ws." ");// The last ws should be the EndPoint

	ws.onopen = function(evt) {
		console.log("Connection open ...");
		ws.send("hello socket!");
	};

	ws.onmessage = function(evt) {
		console.log("receive message: " + evt.data + ":" + (new Date()));
	};

	ws.onclose = function(evt) {
		console.log("Connection closed.Reconnect will be attempted in 1 second.", evt.reason);
		setTimeout(function() {
			ws = wsconnect();
		}, 1000);
	};

	ws.onerror = function(err) {
		console.error('Socket encountered error: ', err.message, 'Closing socket');
		ws.close();
	};

	return ws;
}

$(function(){
	ws = wsconnect();
});
Copy the code