websocket simple communication

Keywords: Session Java Spring JSP

Using websocket can realize full duplex communication between client and server, and the bottom layer is tcp protocol. Principle and concept please Baidu. .

First, we use idea to build a simple web project, and use maven to manage project dependencies. Add spring spring MVN support capability for the project, and add pom dependency as follows:

  <dependency>
      <groupId>javax.websocket</groupId>
      <artifactId>javax.websocket-api</artifactId>
      <version>1.0</version>
    </dependency>

Next, we write the indexes.jsp page generated automatically by the idea as follows: note that the first line of the JSP file here specifies the file code, otherwise it is likely to appear garbled code.

<%@page pageEncoding="utf-8" language="java" %>
<html>
<head>

    <title>web socket</title>
    <script type="text/javascript">
        var webSocket;
        if("WebSocket" in window){
            webSocket=new WebSocket("ws://localhost:80/websocket")

        }

        webSocket.onopen=function(){
            setMessage("websocket Connection opened successfully");
        }
        webSocket.onerror=function (ev) {
            setMessage("websocket error");
        }
        webSocket.onmessage=function (ev) {
            setMessage(ev.data);
        }
        webSocket.onclose=function (ev) {
            setMessage("websocket Close");
        }

        window.onunload=function (ev) {
            closeWebSocket();
        }
        function closeWebSocket(){
            webSocket.close()
        }

        function setMessage(message){
            document.getElementById("div").innerHTML+=message+"<br/>";
        }

        function sendMessage(){
            var content=document.getElementById("message").value;
            webSocket.send(content);
        }
    </script>
</head>
<body>
<h2>webSocket test</h2>
input date:<input type="text" name="message" id="message"/>
<input type="button" name="button" onclick="sendMessage();" value="send"/>
<input type="button" name="button"  onclick="closeWebSocket();" value="close"/>
<div id="div"></div>
</body>
</html>

The above front-end writing is completed. Here, several buttons are set and events are bound to the buttons. In the script, websocket objects are built and events are bound to the objects.

Next is the background part.

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket")
public class webSocketDemo {

    private static  int onlineCount=1;
    private  Session session;

    private static final CopyOnWriteArraySet<webSocketDemo> set=new CopyOnWriteArraySet<>();

    @OnOpen
    public void open(Session session){
        this.session=session;
        System.out.println("===========>open websocket");
        set.add(this);
        add();
    }

    @OnClose
    public void close(){
        set.remove(this);
        del();
        System.out.println("===>Close websocket=======");
    }

    @OnMessage
    public void onMessage(String message,Session session){
        for(webSocketDemo item:set){
            try {
                item.sendMessage("echo"+message);
                System.out.println("send message:+"+message);
            }catch (Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }
    public   void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }
    public static synchronized void add(){
        webSocketDemo.onlineCount++;
    }
    public static synchronized void del(){
        webSocketDemo.onlineCount--;
    }
    
}

The CopyOnWriteArraySet in a java Concurrent package is used here to save each websocket client. In addition, various events are bound to the websocket client to close and open.

 

Here we open two browsers to test the results, as shown below:

Posted by Takuma on Wed, 18 Dec 2019 07:51:20 -0800