1. jar包导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.JAVA代码编写
1. 一对一
package com.youying.websocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value="/websocketServer/{userId}")
public class WebsocketService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private static Map<String,WebsocketService> userMap = new ConcurrentHashMap<>();
private Session session;
private String userId;
@OnOpen
public void onOpen(Session session , @PathParam("roomId") String roomId , @PathParam("userId") String userId) {
logger.info("现在来连接的客户id:"+session.getId()+"用户名:"+userId);
this.session = session;
this.userId = userId;
userMap.put(userId,this);
}
@OnClose
public void onClose(@PathParam("userId") String userId) {
if (userMap.containsKey(userId)) {
userMap.remove(userId);
}
}
@OnMessage
public void onMessage(String message , @PathParam("userId") String userId) {
sendMessageTo(message,userId);
}
public void sendUserTo(String message , String toUserId) {
if (userMap.containsKey(toUserId)) {
userMap.get(toUserId).session.getAsyncRemote().sendText(message);
}
}
}
1. 一对多
package com.youying.websocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value="/websocketServer/{userId}")
public class WebsocketService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private static Map<String,Set<WebsocketService>> userMap = new ConcurrentHashMap<>();
private Session session;
private String userId;
@OnOpen
public void onOpen(Session session , @PathParam("userId") String userId) {
logger.info("现在来连接的客户id:"+session.getId()+"用户名:"+userId);
this.session = session;
this.userId = userId;
if (!userMap .containsKey("001")) {
Set<WebsocketService> user = new HashSet();
user.add(this);
userMap.put("001",user);
} else {
userMap.get("001").add(this);
}
}
@OnClose
public void onClose(@PathParam("userId") String userId) {
if (userMap.containsKey("001")) {
for (WebsocketTest item : roomMap.get("001")) {
if (item.userId.equals(userId)) {
userMap.get("001").remove(item);
}
}
}
}
@OnMessage
public void onMessage(String message , @PathParam("userId") String userId) {
sendMessageTo(message,userId);
}
public void sendUserTo(String message , String toUserId) {
if (userMap.containsKey("001")) {
for (WebsocketTest item : roomMap.get("001")) {
if (!item.userId.equals(toUserId)) {
item.session.getAsyncRemote().sendText(message);
}
}
}
}
多对多
package com.youying.websocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value="/websocketServer/{roomId}/{userId}")
public class WebsocketService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private static Map<String,WebsocketService> userMap = new ConcurrentHashMap<>();
private static Map<String,Set<WebsocketService>> roomMap = new ConcurrentHashMap<>();
private Session session;
private String userId;
@OnOpen
public void onOpen(Session session , @PathParam("roomId") String roomId , @PathParam("userId") String userId) {
logger.info("现在来连接的客户id:"+session.getId()+"用户名:"+userId);
this.session = session;
this.userId = userId;
userMap.put(userId,this);
if (!roomMap.containsKey(roomId)) {
Set<WebsocketService> set = new HashSet<>();
set.add(userMap.get(userId));
roomMap.put(roomId,set);
} else {
roomMap.get(roomId).add(this);
}
}
@OnClose
public void onClose(@PathParam("userId") String userId , @PathParam("roomId") String roomId) {
if (roomMap.containsKey(roomId)) {
Set<WebsocketService> set = roomMap.get(roomId);
for (WebsocketService item : set) {
if (item.userId.equals(userId)) {
set.remove(item);
}
}
}
}
@OnMessage
public void onMessage(String message , @PathParam("roomId") String roomId , @PathParam("userId") String userId) {
sendMessageTo(message,roomId,userId);
}
public void sendMessageTo(String message , String roomId , String userId) {
if (roomMap.containsKey(roomId)) {
for (WebsocketService item : roomMap.get(roomId)) {
if (!item.userId.equals(userId)) {
item.session.getAsyncRemote().sendText(message);
}
}
}
}
public void sendUserTo(String message , String toUserId) {
if (userMap.containsKey(toUserId)) {
userMap.get(toUserId).session.getAsyncRemote().sendText(message);
}
}
}
前端测试页面
<!DOCTYPE HTML>
<html>
<head>
<title>Test My WebSocket2</title>
</head>
<body>
<button onclick="closeWebSocket()">CLOSE</button>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:1216/websocketServer/001/002");
}
else{
alert('Not support websocket')
}
websocket.onerror = function(){
setMessageInnerHTML("error");
};
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
websocket.onclose = function(){
setMessageInnerHTML("close");
}
window.onbeforeunload = function(){
websocket.close();
}
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
function closeWebSocket(){
websocket.close();
}
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
接口测试
package com.youying.controller;
import com.youying.websocket.WebsocketService;
import com.youying.websocket.WebsocketTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
public class WebsocketController {
@Autowired
private WebsocketService websocketService;
@ResponseBody
@GetMapping("/sendOne")
public String sendOne(@RequestParam("message") String message ,
@RequestParam("toUserId") String toUserId) {
websocketService.sendUserTo(message, toUserId);
return "推送成功";
}
@ResponseBody
@GetMapping("/sendUserTo")
public String sendUserTo(@RequestParam("message") String message ,
@RequestParam("userId") String userId) {
websocketService.sendUserTo(message,userId);
return "推送成功";
}
@ResponseBody
@GetMapping("/sendMessageTo")
public String sendMessageTo(@RequestParam("message") String message ,
@RequestParam("roomId") String roomId ,
@RequestParam("userId") String userId) {
websocketService.sendMessageTo(message, roomId, userId);
return "推送成功";
}
}
最好从一对一演变到多对多,其中就是存储的类型的变化,多对多就需要多一个存储变量。
|