What is the WebSocket?

WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5.

WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

In the WebSocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.

Without further ado, it’s dry time.

Maven rely on

SpringBoot2.0’s support for websockets is fantastic, with packages introduced directly

<dependency>  
     <groupId>org.springframework.boot</groupId>  
     <artifactId>spring-boot-starter-websocket</artifactId>  
</dependency> 
Copy the code

WebSocketConfig

Enabling WebSocket support is also very simple, a few lines of code to do

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * enable WebSocket support * @author zhengkai */ @configuration public class WebSocketConfig {@bean public ServerEndpointExporterserverEndpointExporter() {  
        returnnew ServerEndpointExporter(); }}Copy the code

WebSocketServer

Since WebSocket is a client-server-side format (using the WS protocol), @Serverendpoint (“/websocket”); @Component (“/ webSocket “); And then implement @onOpen,@onClose,@onMessage, etc

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import lombok.extern.slf4j.Slf4j;


@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
	
	static Log log=LogFactory.get(WebSocketServer.class); // Static variable, used to record the current number of online connections. It should be designed to be thread-safe. private static int onlineCount = 0; // A thread-safe Set for a concurrent package, used to hold each client's corresponding MyWebSocket object. private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); // A Session is used to connect to a client and send data to the client. Private String SID =""; @onopen public void OnOpen (Session Session, @pathParam ("sid") String sid) { this.session = session; webSocketSet.add(this); / / to joinsetIn addOnlineCount (); // Add 1 log.info("New window starts listening :"+sid+", the number of current online users is" + getOnlineCount());
        this.sid=sid;
        try {
        	 sendMessage("Connection successful");
        } catch (IOException e) {
            log.error("Websocket IO exception"); }} /** * connect to close the called method */ @onclose public voidonClose() { webSocketSet.remove(this); / / fromsetRemove the subOnlineCount (); // Online count minus 1 log.info("There's a connection down! The number of current online users is"+ getOnlineCount()); } /** * @param message public void OnMessage (String message, Session session) { log.info("Received from window"+sid+"Message :"+message); // Group messagefor (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

	/**
	 * 
	 * @param session
	 * @param error
	 */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("Error occurred"); error.printStackTrace(); Public void sendMessage(String Message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * public static void sendInfo(String message, @pathParam ("sid") String sid) throws IOException {
    	log.info("Push message to window"+sid+", push content :"+message);
        for(WebSocketServer item: webSocketSet) {try {// We can set push only to this sid, if null push allif(sid==null) {
            		item.sendMessage(message);
            	}else if(item.sid.equals(sid)){
            		item.sendMessage(message);
            	}
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; }}Copy the code

Being pushed

To push new messages, write a method to call webSocketServer.sendInfo () on your Controller; Can be

@Controller
@RequestMapping("/checkcenter") public class CheckCenterController {// page request @getMapping ("/socket/{cid}")
	public ModelAndView socket(@PathVariable String cid) {
		ModelAndView mav=new ModelAndView("/socket");
		mav.addObject("cid", cid);
		returnmav; } @responseBody@requestMapping ("/socket/push/{cid}")
	public ApiReturnObject pushToWeb(@PathVariable String cid,String message) {  
		try {
			WebSocketServer.sendInfo(message,cid);
		} catch (IOException e) {
			e.printStackTrace();
			return ApiReturnUtil.error(cid+"#"+e.getMessage());
		}  
		returnApiReturnUtil.success(cid); }}Copy the code

The front page

In the page with JS code to call socket, of course, too old browser is not acceptable, general new browser or Google Browser is no problem.

<! DOCTYPE HTML> <html> <head> <meta charset="utf-8"</title> <scripttype="text/javascript">
         function WebSocketTest()
         {
            if ("WebSocket" in window)
            {
               alert("Your browser supports WebSocket!"); Var ws = new WebSocket(Ws: / / "127.0.0.1:8080 / websocket / 1212");
                
               ws.onopen = function() {// The Web Socket is connected, use send() to send data ws.send()"Send data");
                  alert("Data in transit...");
               };
                
               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  alert(received_msg)
                  alert("Data received...");
               };
                
               ws.onclose = function() {// Close websocket alert("Connection closed..."); 
               };
            }
            
            else{// Browsers do not support WebSocket Alert ("Your browser does not support WebSocket!");
            }
         }
      </script>
        
   </head>
   <body>
   
      <div id="sse">
         <a href="javascript:WebSocketTest()"> Run WebSocket</a> </div> </body> </ HTML >Copy the code

run

1. Start the SpringBoot project.

2. Go directly to test.html and click the link

3, the server sends a message:

http://localhost:8080/checkcenter/socket/push/1212?message=xxxx
Copy the code