WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
以上是百度百科给对websocket的解析;其实,以我个人的理解来说,websocket的主要用武之地是全双工;他可以双向数据传送,可以替代服务器有消息需要通知客户端了,可以直接推送过去,而不必非得被动的等着客户端去请求;如果有客户端需要服务器端的一些信息,就只能通过,不断的请求服务器,比如前端编写定时任务;这样有两个弊端,一是太浪费资源,二是实时性也不好;如果使用websocket就可以解决这个问题。服务器端一有消息就立刻推送到客户端,既解决了资源的浪费问题,又解决了实时性的问题
<!--webSocket依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
创建springboot 配置类 将ServerEndpointExporter 交给Spring
@Configuration
public class websocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
创建websocket核心类
package com.study.test.websocket;
import com.fasterxml.jackson.databind.ObjectMapper;
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.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author:linjunbo
* @Description:
* @Date: 2019/11/14 20:00
*/
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
* @ServerEndpoint 可以把当前类变成websocket服务类
*/
@Component
@ServerEndpoint("/websocket/{userId}")
public class websocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户id
private static ConcurrentHashMap<String, websocket> webSocketSet = new ConcurrentHashMap<String, websocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//当前发消息的人员编号
private String userId = "";
/**
* 当链接websocket成功后触发这个方法
*/
@OnOpen
public void onOpen(@PathParam(value = "userId") String param, Session session) {
userId = param;//接收到发送消息的人员编号
this.session = session;
webSocketSet.put(param, this);//加入线程安全map中
addOnlineCount(); //在线数加1
System.out.println("用户id:" + param + "加入连接!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!userId.equals("")) {
webSocketSet.remove(userId); //根据用户id从ma中删除
subOnlineCount(); //在线数减1
System.out.println("用户id:" + userId + "关闭连接!当前在线人数为" + getOnlineCount());
}
}
/**
* 收到客户端消息后调用的方法 重点~~~~
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//要发送人的用户uuid
String sendUserId = message.split(",")[1];
//发送的信息
String sendMessage = message.split(",")[0];
//给指定的人发消息
sendToUser(sendUserId, sendMessage);
}
/**
* 给指定的人发送消息
*
* @param message
*/
public void sendToUser(String sendUserId, String message) {
try {
if (webSocketSet.get(sendUserId) != null) {
webSocketSet.get(sendUserId).sendMessage(userId + "给我发来消息,消息内容为--->>" + message);
} else {
if (webSocketSet.get(userId) != null) {
webSocketSet.get(userId).sendMessage("用户id:" + sendUserId + "以离线,未收到您的信息!");
}
System.out.println("消息接受人:" + sendUserId + "已经离线!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessageTo(String message, String toUserId) throws IOException {
//5 System.out.println("message="+message+" toUserId="+toUserId);
// ObjectMapper mapper = new ObjectMapper();
//String json = mapper.writeValueAsString(message);
//logger.info(toUserId + ", websocket: " + json);
for (websocket item : webSocketSet.values()) {
//System.out.println("item.userId="+item.userId);
//item.session.getBasicRemote().sendText(json);
if(item.userId.equalsIgnoreCase(toUserId)) {
item.session.getBasicRemote().sendText(message);
break;
}
}
}
/**
* 给页面发送消息
*
* @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() {
websocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
websocket.onlineCount--;
}
}
前端页面
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://192.168.129.81:8086/buildingBoard/websocket/TCDZM1" + "@" + new Date().getTime());
}
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");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
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>
调用方法给前端页面发信息
new webSocket.sendMessageTo(message,toUserId);