The following are the construction methods:

First, direct use
the
api
Build.

A total of
Step:

1

Add dependencies

<dependency>

<groupId>javax</groupId>

<artifactId>javaee-api</artifactId>

< version > 7.0 < / version >

<scope>provided</scope>

</dependency>

2

Use annotations
@ServerEndpoint

import javax.websocket.*;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

import java.io.IOException;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

import java.util.logging.Logger;

/ * *

* WebSocket

The connection
sessionKey
is
url
The parameters in the

* /

@ServerEndpoint(“/websocket/{sessionKey}”)

public class WebSocket {

private static final Logger log = Logger.getLogger(WebSocket.class.getName());

//

Static variable that records the number of current online connections. It should be designed to be thread-safe.

private static int onlineCount = 0;

//concurrent

Package thread-safe, used to store each client corresponding
MyWebSocket
Object. If you want to implement communication between a server and a single client, you can use
Map
To store it in
Key
Users can be identified

private static Map<String, WebSocket> webSockets = new ConcurrentHashMap<>();

//

A connection session with a client through which data is sent to the client

private Session session;

/ * *

*

Method successfully called for connection establishment

*

* @param session

Optional parameter.
session
To connect to a client, you need to send data to the client through it

* @param sessionKey url

Address parameter

* /

@OnOpen

public void onOpen(Session session, @PathParam(“sessionKey”) String sessionKey) {

if (! webSockets.containsKey(sessionKey)) {

this.session = session;

webSockets.put(sessionKey, this);

addOnlineCount();

log.info(“

The current
websocket
The number of connections:
” + onlineCount);

}

}

/ * *

*

The connection closes the method called

*

* @param sessionKey url

Address parameter

* /

@OnClose

public void onClose(@PathParam(“sessionKey”) String sessionKey) {

if (webSockets.containsKey(sessionKey)) {

webSockets.remove(sessionKey);

subOnlineCount();

log.info(“

The current
websocket
The number of connections:
” + onlineCount);

}

}

/ * *

*

Method that is invoked after receiving a client message

*

* @param message

The message sent by the client

* @param session

Optional parameter

* /

@OnMessage

public void onMessage(String message, Session session) {

log.info(“

Message from the client
:” + message);

}

/ * *

*

Called when an error occurs

*

* @param session

Optional parameter

* @param error

The error message

* /

@OnError

public void onError(Session session, Throwable error) {

log.info(“websocket

Error:
” + error);

}

/ * *

*

This method has no annotations and is added as needed. Called in their own business, sending messages to the front end.

*

* @param sessionKey

* @param message

Return result

* @throws IOException

* /

public static void sendMessage(String sessionKey, String message) throws IOException {

WebSocket webSocket = webSockets.get(sessionKey);

if (null ! = webSocket) {

log.info(“websocket

Send a message:
” + message);

//

Synchronous sending When sending the second message, wait until the first message is sent

webSocket.session.getBasicRemote().sendText(message);

//

Asynchronous send

//webSocket.session.getAsyncRemote().sendText(message);

}

}

public static synchronized int getOnlineCount() {

return onlineCount;

}

public static synchronized void addOnlineCount() {

onlineCount++;

}

public static synchronized void subOnlineCount() {

onlineCount–;

}

}

3

, test,

online
Testing:
http://coolaf.com/tool/chattest

Enter the address to test, for example:

Addendum: Can also be used
Set up the client application test, the test routine is left behind
~ ~

Second, and
Integration of
WebSocket
service
(
More powerful
)

Take a look at the effect:

http://localhost:8080/websocket/sendToUser?username=river&info=

What do you want with me?

maven

Dependencies are as follows:

maven

Dependencies are as follows:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-websocket</artifactId>

< version > 2.0.4. RELEASE < / version >

</dependency>

1

, the control class

package com.boot.river.websocket;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.socket.TextMessage;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

@Controller

@RequestMapping(value = “/websocket”, method = {RequestMethod.POST, RequestMethod.GET})/*GET

Requests are open for testing, preferably only allowed
POST
request
* /

public class WebSocketController {

@Autowired

SpringWebSocketHandler springWebSocketHandler;

/ * *

*

Log in to
username
In the
session
In and then in the interceptor
HandshakeInterceptor
Remove the

* /

@ResponseBody

@RequestMapping(“/login”)

public String login(HttpServletRequest request, @RequestParam(value = “username”) String username, @RequestParam(value = “password”) String password) {

System.out.println(“

Login:
” + username + ”
:
” + password);

HttpSession session = request.getSession();

if (null ! = session) {

session.setAttribute(“SESSION_USERNAME”, username);

return “success”;

} else {

return “fail”;

}

}

/ * *

*

Specify the send

* /

@ResponseBody

@RequestMapping(“/sendToUser”)

public String send(@RequestParam(value = “username”) String username, @RequestParam(value = “info”) String info) {

springWebSocketHandler.sendMessageToUser(username, new TextMessage(info));

System.out.println(“

Send to:
” + username);

return “success”;

}

/ * *

*

radio

* /

@ResponseBody

@RequestMapping(“/broadcast”)

public String broadcast(@RequestParam(value = “info”) String info) {

springWebSocketHandler.sendMessageToUsers(new TextMessage(“

Broadcast message:
” + info));

System.out.println(“

Broadcast success
“);

return “success”;

}

}

2

, configuration class (implementation
WebSocketConfigurer
Interface)

@Configuration

@EnableWebSocket

public class SpringWebSocketConfig implements WebSocketConfigurer {

public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

registry.addHandler(getSpringWebSocketHandler(), “/websocket/server”)

.addInterceptors(getInterceptor()).setAllowedOrigins(“*”);

registry.addHandler(getSpringWebSocketHandler(), “/sockjs/server”).setAllowedOrigins(“*”)

.addInterceptors(getInterceptor()).withSockJS();

}

@Bean

public SpringWebSocketHandler getSpringWebSocketHandler() {

return new SpringWebSocketHandler();

}

@Bean

public SpringWebSocketHandlerInterceptor getInterceptor() {

return new SpringWebSocketHandlerInterceptor();

}

}

3

, the processing class (implemented
WebSocketHandler
Interface)

package com.boot.river.websocket;

import org.springframework.web.socket.CloseStatus;

import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;

import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

public class SpringWebSocketHandler extends TextWebSocketHandler {

/ * *

*

Storing user
id
And its corresponding
session

* /

private static final Map<String, WebSocketSession> users = new HashMap<>();

/ * *

*

The user name
key
value

* /

private static final String USER_ID = “WEBSOCKET_USERID”;

/ * *

*

Triggered after the connection is established

* /

@Override

public void afterConnectionEstablished(WebSocketSession session) {

System.out.println(“

Successfully established
websocket
The connection
!” );

String userId = (String) session.getAttributes().get(USER_ID); //

Retrieves the object stored in the interceptor
username

users.put(userId, session);

System.out.println(“

Number of current online users
:” + users.size());

}

/ * *

*

Triggered when the connection is closed

* /

@Override

public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {

String userId = (String) session.getAttributes().get(USER_ID);

System.out.println(“

The user
” + userId + ”
Has quit!
“);

users.remove(userId);

System.out.println(“

Remaining online users
” + users.size());

}

/ * *

*

Receives the message

* /

@Override

protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

super.handleTextMessage(session, message);

System.out.println(“

Received a message:
” + message);

if (message.getPayload().contains(“

In?
“)) {

session.sendMessage(new TextMessage(“

You’re not online!
“));

}

}

public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

if (session.isOpen()) {

session.close();

}

System.out.println(“

The transmission is abnormal and shut down
websocket
The connection
. “);

String userId = (String) session.getAttributes().get(USER_ID);

users.remove(userId);

}

public boolean supportsPartialMessages() {

return false;

}

/ * *

*

Send a message to a user

* /

public void sendMessageToUser(String userId, TextMessage message) {

for (String id : users.keySet()) {

if (id.equals(userId)) {

try {

if (users.get(id).isOpen()) {

users.get(id).sendMessage(message);

}

} catch (IOException e) {

e.printStackTrace();

}

break;

}

}

}

/ * *

*

Send messages to all online users

* /

public void sendMessageToUsers(TextMessage message) {

for (String userId : users.keySet()) {

try {

if (users.get(userId).isOpen()) {

users.get(userId).sendMessage(message);

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

4

Interceptor (implementation
HandshakeInterceptor
Interface)

package com.boot.river.websocket;

import org.springframework.http.server.ServerHttpRequest;

import org.springframework.http.server.ServerHttpResponse;

import org.springframework.http.server.ServletServerHttpRequest;

import org.springframework.web.socket.WebSocketHandler;

import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;

import java.util.Map;

public class SpringWebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {

@Override

public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,

Map<String, Object> attributes) throws Exception {

System.out.println(“Before Handshake”);

if (request instanceof ServletServerHttpRequest) {

ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;

HttpSession session = servletRequest.getServletRequest().getSession(false); //

To obtain
session
If not, returns
null

if (session ! = null) {

String userName = (String) session.getAttribute(“SESSION_USERNAME”); //

The user name saved at login

if (userName ! = null) {

attributes.put(“WEBSOCKET_USERID”, userName); //

In the
attributes
Can be in the processor
WebSocketSession
Remove the

}

}

}

return super.beforeHandshake(request, response, wsHandler, attributes);

}

@Override

public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,

Exception ex) {

super.afterHandshake(request, response, wsHandler, ex);

System.out.println(“after Handshake”);

}

}

Reference:

https://my.oschina.net/u/3445245/blog/3003208

https://blog.csdn.net/runbat/article/details/80985944

https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/websocket.html

The following are introduced separately
the
java
The client requests and
js
Client request

1

,
java
The client

Add dependencies:

<dependency>

<groupId>org.java-websocket</groupId>

<artifactId>Java-WebSocket</artifactId>

The < version > 1.4.0 < / version >

</dependency>

package com.river.websocket;

import org.java_websocket.enums.ReadyState;

import java.net.URISyntaxException;

/ * *

* @author river

* @date 2019-12-6

* /

public class Client {

public static void main(String[] args) throws URISyntaxException, InterruptedException {

MyWebSocketClient client = new MyWebSocketClient(“ws://localhost:8080/websocket/server”);

client.connect();

while (client.getReadyState() ! = ReadyState.OPEN) {

System.out.println(“

Connection status:
” + client.getReadyState());

Thread.sleep(100);

}

client.send(“

Test data!
“);

client.close();

}

}

inheritance

package com.river.websocket;

import org.java_websocket.client.WebSocketClient;

import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import java.net.URISyntaxException;

public class MyWebSocketClient extends WebSocketClient {

MyWebSocketClient(String url) throws URISyntaxException {

super(new URI(url));

}

@Override

public void onOpen(ServerHandshake shake) {

System.out.println(shake.getHttpStatusMessage());

}

@Override

public void onMessage(String paramString) {

System.out.println(paramString);

}

@Override

public void onClose(int paramInt, String paramString, boolean paramBoolean) {

System.out.println(“

Shut down
“);

}

@Override

public void onError(Exception e) {

System.out.println(“

An error occurred
“);

}

}

2

,
js
The client

<! DOCTYPE html>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>

<title>websocket</title>

< script type = “text/javascript” SRC = “http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js” > < / script >

< script type = “text/javascript” SRC = “http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.js” > < / script >

<script type=”text/javascript”>

var websocket = null;

if (‘WebSocket’ in window) {

websocket = new WebSocket(“ws://localhost:8080/websocket/server”);

} else if (‘MozWebSocket’ in window) {

websocket = new MozWebSocket(“ws://localhost:8080/websocket/server”);

} else {

websocket = new SockJS(“http://localhost:8080/sockjs/server”);

}

websocket.onopen = onOpen;

websocket.onmessage = onMessage;

websocket.onerror = onError;

websocket.onclose = onClose;

function onOpen(event) {

alert(event.type);

}

function onMessage(messageEvent) {

alert(messageEvent.data);

}

function onError(event) {

}

function onClose(closeEvent) {

alert(closeEvent.reason);

}

function doSendUser() {

if (websocket.readyState === websocket.OPEN) {

var msg = document.getElementById(“inputMsg”).value;

websocket.send(msg); //

Send a message

alert(“

Send a success
!” );

} else {

alert(“

The connection fails
!” );

}

}

window.close = function () {

websocket.onclose();

};

function websocketClose() {

websocket.close();

alert(“

Connection is closed
“);

}

</script>

</head>

<body>

Please enter:

<button

&western
nclick=”doSendUser();” >
send
</button>

<button

&western
nclick=”websocketClose();” >
Close the connection
</button>

</body>

</html>

Addendum: In addition to being handled in Controller, login can also be handled in Websocket for messages received.