什么是WebSocket
WebSocket是HTML5提供的一种基于TCP协议的双向通信协议。WebSocket的出现解决了服务器主动向客户端发送消息的难题。在WebSocket API中,只需要客户端与服务器完成一次握手,两者之间就可以建立长时间的链接,并进行双向数据的传输。
WebSocket的出现解决什么问题
在以前很多公司为了实现推送技术所用的技术是Ajax轮询,也就是定时的向服务器发送HTTP请求,然后由服务器返回最新的数据给客户端。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
两种模式的对比:
Spring boot 整合 WebSocket
- 引入spring boot整合websocket所需的jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 添加WebSocket的配置
/**
* @Created by leyangjie
* @Date 2019/4/14 15:37
* @Description: 开启对WebSocket的支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
- 设置WebSocket 服务端
/**
* @Created by leyangjie
* @Date 2019/4/14 15:40
* @Description: webSocket服务端
*/
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
/**
* 当前在线人数,应该设置为线程安全的
*/
private static int onlineNum = 0;
/**
* concurrent包下线程安全的Set
*/
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
/**
* 与客户端的连接会话,需要它给客户端发送消息
*/
private Session session;
/**
* 登录用户id
*/
private Long userId;
/**
* 建立连接时调用
* @param session 服务端与客户端连接的会话
* @param userId 登录用户id
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") Long userId){
this.session = session;
this.userId = userId;
//添加到set集合
webSocketSet.add(this);
//在线人数 +1
addOnlineCount();
log.info("有新用户登录,用户id为{},当前登录总人数为{}",userId,getTotalCount());
try {
//向客户端发送消息
sendMessage("连接成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") Long sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个userId的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.userId.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
/**
* 断开连接时调用
*/
public void onClose(){
//删除当前对象
webSocketSet.remove(this);
//在线人数 -1
subOnlineCount();
}
/**
* 发送错误时调用
* @param session
* @param throwable
*/
@OnError
public void onError(Session session,Throwable throwable){
log.error("出错了。。。");
throwable.printStackTrace();
}
/**
* 收到客户端消息时调用
*/
@OnMessage
public void onMessage(String message,Session session) throws IOException {
log.info("收到{}用户发送来的{}信息",userId,message);
for (WebSocketServer socketServer : webSocketSet) {
socketServer.sendMessage(message);
}
}
private synchronized void subOnlineCount() {
onlineNum -- ;
}
/**
* 服务端向客户端发送消息
* @param message
*/
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
private int getTotalCount() {
return webSocketSet.size();
}
private synchronized void addOnlineCount() {
onlineNum ++ ;
}
}
- 新建 Controller接受http请求,给client发送消息
@RestController
@RequestMapping("/checkcenter")
public class CheckCenterController {
//推送数据接口
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public String pushToWeb(@PathVariable Long cid, String message) {
try {
WebSocketServer.sendInfo(message,cid);
} catch (IOException e) {
e.printStackTrace();
}
return "发送成功!";
}
}
- 新建客户端应用
新建文件并命名为 websocket.html
向服务端发送一次握手,建立长连接
<html>
<head><title>websocket</title></head>
<body>
<script>
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
socket = new WebSocket("ws://localhost:8080/websocket/20".replace("http","ws"));
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
</script>
</body>
</html>
启动后台应用,端口默认为8080,使用浏览器打开我们的websocket.html文件,我们打开console可以看到已经跟后台服务建立连接了。
我们的WebSocketServer控制台,也调用onOpen方法,信息打印到控制台.
当我们使用 http://localhost:8080/checkcenter//socket/push/20?message=你好吗 使用Http调用后台服务,给前台发送消息。WebSocketServer服务控制台有日志打印
WebSocket.html控制台收到后台服务发送的消息。
`