1
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
< version > 7.0 < / version >
<scope>provided</scope>
</dependency>
2
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
* /
@ServerEndpoint(“/websocket/{sessionKey}”)
public class WebSocket {
private static final Logger log = Logger.getLogger(WebSocket.class.getName());
//
private static int onlineCount = 0;
//concurrent
private static Map<String, WebSocket> webSockets = new ConcurrentHashMap<>();
//
private Session session;
/ * *
*
*
* @param session
* @param sessionKey url
* /
@OnOpen
public void onOpen(Session session, @PathParam(“sessionKey”) String sessionKey) {
if (! webSockets.containsKey(sessionKey)) {
this.session = session;
webSockets.put(sessionKey, this);
addOnlineCount();
log.info(“
}
}
/ * *
*
*
* @param sessionKey url
* /
@OnClose
public void onClose(@PathParam(“sessionKey”) String sessionKey) {
if (webSockets.containsKey(sessionKey)) {
webSockets.remove(sessionKey);
subOnlineCount();
log.info(“
}
}
/ * *
*
*
* @param message
* @param session
* /
@OnMessage
public void onMessage(String message, Session session) {
log.info(“
}
/ * *
*
*
* @param session
* @param error
* /
@OnError
public void onError(Session session, Throwable error) {
log.info(“websocket
}
/ * *
*
*
* @param sessionKey
* @param message
* @throws IOException
* /
public static void sendMessage(String sessionKey, String message) throws IOException {
WebSocket webSocket = webSockets.get(sessionKey);
if (null ! = webSocket) {
log.info(“websocket
//
webSocket.session.getBasicRemote().sendText(message);
//
//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
http://localhost:8080/websocket/sendToUser?username=river&info=
maven
maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
< version > 2.0.4. RELEASE < / version >
</dependency>
1
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
public class WebSocketController {
@Autowired
SpringWebSocketHandler springWebSocketHandler;
/ * *
*
* /
@ResponseBody
@RequestMapping(“/login”)
public String login(HttpServletRequest request, @RequestParam(value = “username”) String username, @RequestParam(value = “password”) String password) {
System.out.println(“
HttpSession session = request.getSession();
if (null ! = session) {
session.setAttribute(“SESSION_USERNAME”, username);
return “success”;
} else {
return “fail”;
}
}
/ * *
*
* /
@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(“
return “success”;
}
/ * *
*
* /
@ResponseBody
@RequestMapping(“/broadcast”)
public String broadcast(@RequestParam(value = “info”) String info) {
springWebSocketHandler.sendMessageToUsers(new TextMessage(“
System.out.println(“
return “success”;
}
}
2
@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
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 {
/ * *
*
* /
private static final Map<String, WebSocketSession> users = new HashMap<>();
/ * *
*
* /
private static final String USER_ID = “WEBSOCKET_USERID”;
/ * *
*
* /
@Override
public void afterConnectionEstablished(WebSocketSession session) {
System.out.println(“
String userId = (String) session.getAttributes().get(USER_ID); //
users.put(userId, session);
System.out.println(“
}
/ * *
*
* /
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
String userId = (String) session.getAttributes().get(USER_ID);
System.out.println(“
users.remove(userId);
System.out.println(“
}
/ * *
*
* /
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
super.handleTextMessage(session, message);
System.out.println(“
if (message.getPayload().contains(“
session.sendMessage(new TextMessage(“
}
}
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if (session.isOpen()) {
session.close();
}
System.out.println(“
String userId = (String) session.getAttributes().get(USER_ID);
users.remove(userId);
}
public boolean supportsPartialMessages() {
return false;
}
/ * *
*
* /
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;
}
}
}
/ * *
*
* /
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
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); //
if (session ! = null) {
String userName = (String) session.getAttribute(“SESSION_USERNAME”); //
if (userName ! = null) {
attributes.put(“WEBSOCKET_USERID”, userName); //
}
}
}
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”);
}
}
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
1
<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(“
Thread.sleep(100);
}
client.send(“
client.close();
}
}
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(“
}
@Override
public void onError(Exception e) {
System.out.println(“
}
}
2
<! 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); //
alert(“
} else {
alert(“
}
}
window.close = function () {
websocket.onclose();
};
function websocketClose() {
websocket.close();
alert(“
}
</script>
</head>
<body>
<button
<button
</body>
</html>