1. 什么是websocket?
websocket是HTML5提供的一种在单个TCP连接上进行全双工通信的协议,允许服务器主动向客户端推送数据。
全双工:客户端与浏览器一旦连接建立之后的通信则使用双向模式交互,不论是客户端还是服务端都可以随时将数据发送给对方。
2. http协议与websocket协议交互
3. http与websocket协议格式的不同
WebSocket与HTTP的协议格式是完全不同的,具体来讲:
(1)HTTP协议(参见:rfc2616)比较臃肿,而WebSocket协议比较轻量。
(2)对于HTTP协议来讲,一个数据包就是一条完整的消息;而WebSocket客户端与服务端通信的最小单位是帧(frame),由1个或多个帧组成一条完整的消息(message)。即:发送端将消息切割成多个帧,并发送给服务端;服务端接收消息帧,并将关联的帧重新组装成完整的消息。
4.Springboot整合websocket
4.1 pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
4.2 添加webSocketConfig配置类
/**
* 开启WebSocket支持
* Created by dkx on 2019/12/21.
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
4.3 添加webSocketServer服务端类
@ServerEndpoint("/websocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法
* */
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
*/
/**
* 连接关闭调用的方法
* */
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
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();
}
}
}
*/
@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--;
}
public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
return webSocketSet;
}
}
4.4 添加对应的controller
@RestController
@RequestMapping("/websocket")
public class SystemController {
//推送数据接口
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public Map pushToWeb(@PathVariable String cid, String message) {
Map result = new HashMap();
try {
WebSocketServer.sendInfo(message,cid);
result.put("code", 200);
result.put("msg", "success");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
遇到的问题:
1.WebSocketServer被德鲁伊日志进行了切面,这个类被cglib代理了,导致找不到@ServerEndpoint注解。
2.发送消息时出现了线程安全的问题。
原因:websocket发送消息的时候会通过一个状态机管理状态,状态为OPEN的时候才允许调用发送方法,调用发送方法后状态修改为TEXT_FULL_WRITING,此时其他线程再调用发送方法就会报状态错误,当正在写的线程写完的时候状态会重新改为OPEN,这时候才能再次调用发送方法。(多个线程向一个socket写数据冲突了)