1、首先pom中引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、创建WebSocketConfig
/**
* @author : 徐长城
* @des:
* @date : 2019/9/18 20:44
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、创建Server
/**
* @author : 徐长城
* @des:
* @date : 2019/9/18 21:12
*/
@ServerEndpoint(value = "/websocket/{id}")
@Component
public class WebSocketServer {
// 用于存储socketServer
private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private static Logger log = LogManager.getLogger(WebSocketServer.class);
private String id = "";
/**
* 连接建立成功
* @param id
* @param session
*/
@OnOpen
public void onOpen(@PathParam(value = "id") String id, Session session) {
this.session = session;
this.id = id;
webSocketSet.put(id, this);
log.info("用户"+id+"连接成功!当前人数:"+webSocketSet.size());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam(value = "id") String id) {
System.out.println("id:::"+id);
webSocketSet.remove(id); //从set中删除
log.info("有一连接关闭!当前在线人数为"+webSocketSet.size());
}
/**
* 异常
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 发送信息
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 发送指定用户消息
* @param message
* @param id
* @throws IOException
*/
public void sendtoUser(String message,String id) throws IOException {
if (webSocketSet.get(id) != null) {
webSocketSet.get(id).sendMessage(message);
}
}
}
写一个Controller作为生产消息
/**
* @author : 徐长城
* @des: 用于生产消息
* @date : 2019/9/18 21:31
*/
@RestController
@RequestMapping("/production")
public class TestController {
@Autowired
private WebSocketServer webSocketServer;
/**
* 此Controller主要是用来测试的,实际开发不能这些写
*
*/
/**
* 向用户一推送数据
* @param msg
* @return
*/
@GetMapping("/yonghu1")
public Map<String,Object> yonghu1(String msg){
Map<String,Object> map = new HashMap<>();
try {
webSocketServer.sendtoUser(msg,"1");
map.put("id",1);
map.put("msg",msg);
map.put("status",0);
} catch (IOException e) {
e.printStackTrace();
map.put("id",1);
map.put("msg",msg);
map.put("status",1);
}
return map;
}
/**
* 向用户二推送数据
* @param msg
* @return
*/
@GetMapping("/yonghu2")
public Map<String,Object> yonghu2(String msg){
Map<String,Object> map = new HashMap<>();
try {
webSocketServer.sendtoUser(msg,"2");
map.put("id",2);
map.put("msg",msg);
map.put("status",0);
} catch (IOException e) {
e.printStackTrace();
map.put("id",2);
map.put("msg",msg);
map.put("status",1);
}
return map;
}
}
写2个界面用来模拟2个不用不同用户,用来验证,推送消息是否能准确推送到某个人
one.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
用户一
<p id="text"></p>
<script>
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
socket = new WebSocket("ws://localhost:8080/websocket/1");
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
document.getElementById('text').innerHTML = msg.data;
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
}
//关闭连接
function closeWebSocket() {
socket.close();
}
}
</script>
</body>
</html>
two.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
用户二
<p id="text"></p>
<script>
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
socket = new WebSocket("ws://localhost:8080/websocket/2");
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
document.getElementById('text').innerHTML = msg.data;
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
}
//关闭连接
function closeWebSocket() {
socket.close();
}
}
</script>
</body>
</html>
向一推送信息
向二推送信息