WebSocket 协议是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工 (full-duplex) 通讯—容许服务器主动发送信息给客户端。前端
你们都知道之前客户端想知道服务端的处理进度,要不停地使用 Ajax 进行轮询,让浏览器隔个几秒就向服务器发一次请求,这对服务器压力较大。另一种轮询就是采用 long poll 的方式,这就跟打电话差很少,没收到消息就一直不挂电话,也就是说,客户端发起链接后,若是没消息,就一直不返回 response 给客户端,链接阶段一直是阻塞的。java
而 WebSocket 解决了 HTTP 的这几个难题。当服务器完成协议升级后( HTTP -> WebSocket ),服务端能够主动推送信息给客户端,解决了轮询形成的同步延迟问题。因为 WebSocket 只须要一次 HTTP 握手,服务端就能一直与客户端保持通讯,直到关闭链接,这样就解决了服务器须要反复解析 HTTP 协议,减小了资源的开销。jquery
如今经过 SpringBoot 集成 WebSocket 来实现先后端通讯。web
项目代码结构图 spring
SpringBoot2.0 对 WebSocket 的支持简直太棒了,直接就有包能够引入 。后端
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
复制代码
启用WebSocket的支持也是很简单,将ServerEndpointExporter对象注入到容器中。浏览器
package com.tuhu.websocketsample.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
复制代码
由于 WebSocket 是相似客户端服务端的形式(采用ws协议),那么这里的 WebSocketServer 其实就至关于一个 ws协议的 Controller。直接 @ServerEndpoint("/websocket") 、@Component 启用便可,而后在里面实现@OnOpen , @onClose ,@onMessage等方法tomcat
package com.tuhu.websocketsample.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/websocket/{sid}")
@Slf4j
public class WebSocketServer {
/**
* 静态变量,用来记录当前在线链接数。应该把它设计成线程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的线程安全Set,用来存放每一个客户端对应的MyWebSocket对象。
*/
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
/**
* 与某个客户端的链接会话,须要经过它来给客户端发送数据
*/
private Session session;
/**
* 接收sid
*/
private String sid="";
/**
* 链接创建成功调用的方法
**/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
//加入set中
webSocketSet.add(this);
//在线数加1
addOnlineCount();
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("链接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 链接关闭调用的方法
*/
@OnClose
public void onClose() {
//从set中删除
webSocketSet.remove(this);
//在线数减1
subOnlineCount();
log.info("有一链接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
**/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里能够设定只推送给这个sid的,为null则所有推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
复制代码
至于推送新信息,能够再本身的 Controller 写个方法调用 WebSocketServer.sendInfo() 便可安全
package com.tuhu.websocketsample.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
@RestController
@RequestMapping("/checkcenter")
public class CheckCenterController {
/**
* 页面请求
* @param cid
* @return
*/
@GetMapping("/socket/{cid}")
public ModelAndView socket(@PathVariable String cid) {
ModelAndView mav=new ModelAndView("/socket");
mav.addObject("cid", cid);
return mav;
}
/**
* 推送数据接口
* @param cid
* @param message
* @return
*/
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public String pushToWeb(@PathVariable String cid,String message) {
try {
WebSocketServer.sendInfo(message,cid);
} catch (IOException e) {
e.printStackTrace();
return "error:"+cid+"#"+e.getMessage();
}
return "success:"+cid;
}
}
复制代码
而后在页面用js代码调用 socket,固然,太古老的浏览器是不行的,通常新的浏览器或者谷歌浏览器是没问题的。还有一点,记得协议是ws的哦。直接在浏览器控制台开启链接。服务器
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要链接的服务器地址与端口 创建链接
socket = new WebSocket("ws://localhost:8080/websocket/20");
//打开事件
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();
//});
}
复制代码
如今能够在浏览器开启链接,经过客户端调用接口服务端就能够向浏览器发送消息。
如今打开两个页面开启两个链接:
向前端推送数据:
能够看到服务端已经将消息推送给了客户端
而客户端也收到了消息
先打开页面,指定cid,启用socket接收,而后再另外一个页面调用刚才Controller封装的推送信息的方法到这个cid的socket,便可向前端推送消息。
serverEndpointExporter 错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘serverEndpointExporter’ defined in class path resource [com/xxx/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available
若是 tomcat 部署一直报这个错,请移除 WebSocketConfig 中 @Bean ServerEndpointExporter 的注入 。
ServerEndpointExporter 是由 Spring 官方提供的标准实现,用于扫描 ServerEndpointConfig 配置类和@ServerEndpoint 注解实例。使用规则也很简单:
一、若是使用默认的嵌入式容器 好比Tomcat 则必须手工在上下文提供ServerEndpointExporter。
二、若是使用外部容器部署war包,则不须要提供提供ServerEndpointExporter,由于此时SpringBoot默认将扫描 服务端的行为交给外部容器处理,因此线上部署的时候要把WebSocketConfig中这段注入bean的代码注掉。