In a recent project, I needed to use the new features of Java websocket, so I learned it and felt that this technology was quite fun. I instantly knew how the online customer service on the web page was done.
Let's look at the picture first:
Real-time communication between multiple clients is realized.
Let’s look at the code project structure diagram: It’s very simple, just 1 class and 1 page
Then look at the specific code
Look at the backend code first
package com.main;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet;import javax.websocket.*;import javax.websocket.server.ServerEndpoint;/** * @ServerEndpoint The annotation is a class-level annotation. Its function is mainly to define the current class as a websocket server side. * The annotation value will be used to listen to the user's connection to the terminal access URL address. The client can connect to the WebSocket server side through this URL*/@ServerEndpoint("/websocket")public class H5ServletServerSocket { // Static variables used to record the current number of online connections. It should be designed to be thread-safe. private static int onlineCount = 0; // The thread-safe Set of the concurrent package is used to store the corresponding MyWebSocket object of each client. To realize that the server communicates with a single client, you can use Map to store it, where the Key can identify the user private static CopyOnWriteArraySet<H5ServletServerSocket> webSocketSet = new CopyOnWriteArraySet<H5ServletServerSocket>(); // A connection session with a certain client needs to send data to the client private Session session; /** * Method for successfully calling connection establishment* * @param session * Optional parameters. session is a connection session with a client, and it needs to send data to the client through it*/ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); // AddOnlineCount() in set; // Add 1 online number System.out.println("There is a new connection to join! The current number of online people is" + getOnlineCount()); } /** * Method for connecting closing calls*/ @OnClose public void onClose() { webSocketSet.remove(this); // Remove subOnlineCount() from set; // Delete subOnlineCount() from set; // Delete online number by 1 online number System.out.println("There is a connection closed! The current number of people online is" + getOnlineCount()); } /** * Method called after receiving the client message* * @param message * Message sent by the client* @param session * Optional parameters*/ @OnMessage public void onMessage(String message, Session session) { System.out.println("Message from the client:" + message); // Bulk message for (H5ServletServerSocket item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } } } } /** * Called when an error occurs * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println("Error occurred"); error.printStackTrace(); } /** * This method is different from the above methods. There is no annotation, it is a method added according to your needs. * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); // this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { H5ServletServerSocket.onlineCount++; } public static synchronized void subOnlineCount() { H5ServletServerSocket.onlineCount--; }}Next is the front-end page code:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><!DOCTYPE HTML><html><head><base href="<%=basePath%>"><title>My WebSocket</title></head><body> Welcome to the chat room<div id="message" style="color: blue">【Status】</div> <br /> Nickname<input id="username" type="text" required="required"/> <br> Content<input id="text" type="text" /> <br /> <button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button></body><script type="text/javascript"> var websocket = null; //Judge whether the current browser supports WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://10.1.1.106:8080/Socket/websocket"); } else { alert('WebSocket not supported!') } //Callback method for errors in connection websocket.onerror = function() { setMessageInnerHTML("error"); }; //Callback method for successful connection websocket.onopen = function(event) { setMessageInnerHTML("Chat room enabled"); } //Callback method for receiving message websocket.onmessage = function() { setMessageInnerHTML(event.data); } //Connection closed callback method websocket.onclose = function() { setMessageInnerHTML("Chat Room Close"); } // Listen to the window closing event. When the window is closed, actively close the websocket connection to prevent the window from closing before the connection is disconnected, and the server side will throw exceptions. window.onbeforeunload = function() { websocket.close(); } //Show the message on the web page function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //Close the connection function closeWebSocket() { websocket.close(); } //Send the message function send() { var username = document.getElementById('username').value; var message = document.getElementById('text').value; var msg = "【" + username + "]Speak:" + message websocket.send(msg); }</script></html>The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.