认识WebSocket并搭建服务端
前言
一、概述
WebSocket 协议在2008年诞生,2011年成为国际标准。webSocket能够在建立连接之后,在服务器端推送数据到客户端,解决HTTP协议的弊端。
特点:
(1)建立在 TCP 协议之上,服务器端的实现比较容易。
(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
(3)数据格式比较轻量,性能开销小,通信高效。
(4)可以发送文本,也可以发送二进制数据。
(5)没有同源限制,客户端可以与任意服务器通信。
(6)协议标识符是ws (如果加密,则为wss ),服务器网址就是 URL。
为什么需使用webSocket?
因为HTTP协议的通信只能由客户端发起,无法服务端主动推送数据。我们当然可以使用HTTP然后轮询探测数据变化,但效率低,性能差,不建议使用。
二、客户端说明
1.新建 WebSocket 实例
var ws = new WebSocket('ws://localhost:8080');
2.webSocket.readyState
readyState 属性返回实例对象的当前状态,共有四种。
- CONNECTING:值为0,表示正在连接。
- OPEN:值为1,表示连接成功,可以通信了。
- CLOSING:值为2,表示连接正在关闭。
- CLOSED:值为3,表示连接已经关闭,或者打开连接失败。
3.webSocket.onopen
onopen 属性,用于指定连接成功后的回调函数。
4.webSocket.onclose
onclose 属性,用于指定连接关闭后的回调函数。
5.webSocket.onmessage
onmessage 属性,用于指定收到服务器数据后的回调函数。
6.webSocket.send()
send() 方法用于向服务器发送数据。
7.webSocket.bufferedAmount
bufferedAmount 属性,表示还有多少字节的二进制数据没有发送出去。它可以用来判断发送是否结束。
8.webSocket.onerror
onerror 属性,用于指定报错时的回调函数。
三、服务端说明
常用的 Node 实现有以下三种。
Java搭建webSocket服务
使用SpringBoot作为基础环境
导入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
添加webSocket配置:
package cn.hacah.websocketdemo.config;
import cn.hacah.websocketdemo.handle.SpringWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class SpringWebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(getSpringWebSocketHandler(), "/websocket/server")
.addInterceptors(getInterceptor()).setAllowedOrigins("*");
registry.addHandler(getSpringWebSocketHandler(), "/sockjs/server").setAllowedOrigins("*")
.addInterceptors(getInterceptor()).withSockJS();
}
@Bean
public SpringWebSocketHandler getSpringWebSocketHandler() {
return new SpringWebSocketHandler();
}
@Bean
public SpringWebSocketHandlerInterceptor getInterceptor() {
return new SpringWebSocketHandlerInterceptor();
}
}
拦截器:
package cn.hacah.websocketdemo.config;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import javax.servlet.http.HttpSession;
import java.util.Map;
public class SpringWebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
System.out.println("Before Handshake");
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
if (session != null) {
String userName = (String) session.getAttribute("SESSION_USERNAME");
if (userName != null) {
attributes.put("WEBSOCKET_USERID", userName);
}
}
}
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
super.afterHandshake(request, response, wsHandler, ex);
System.out.println("after Handshake");
}
}
webSocket处理代码
package cn.hacah.websocketdemo.handle;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class SpringWebSocketHandler extends TextWebSocketHandler {
private static final Map<String, WebSocketSession> users = new HashMap<>();
private static final String USER_ID = "WEBSOCKET_USERID";
@Override
public void afterConnectionEstablished(WebSocketSession session) {
System.out.println("成功建立websocket连接!");
String userId = (String) session.getAttributes().get(USER_ID);
users.put(userId, session);
System.out.println("当前线上用户数量:" + users.size());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
String userId = (String) session.getAttributes().get(USER_ID);
System.out.println("用户" + userId + "已退出!");
users.remove(userId);
System.out.println("剩余在线用户" + users.size());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
super.handleTextMessage(session, message);
System.out.println("收到消息:" + message);
if (message.getPayload().contains("在吗")) {
session.sendMessage(new TextMessage("对方不在线!"));
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if (session.isOpen()) {
session.close();
}
System.out.println("传输出现异常,关闭websocket连接... ");
String userId = (String) session.getAttributes().get(USER_ID);
users.remove(userId);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
public void sendMessageToUser(String userId, TextMessage message) {
for (String id : users.keySet()) {
if (id.equals(userId)) {
try {
if (users.get(id).isOpen()) {
users.get(id).sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
public void sendMessageToUsers(TextMessage message) {
for (String userId : users.keySet()) {
try {
if (users.get(userId).isOpen()) {
users.get(userId).sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
controller代码:
package cn.hacah.websocketdemo.controller;
import cn.hacah.websocketdemo.handle.SpringWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping(value = "/websocket", method = {RequestMethod.POST, RequestMethod.GET})
public class WebSocketController {
@Autowired
SpringWebSocketHandler springWebSocketHandler;
@ResponseBody
@RequestMapping("/login")
public String login(HttpServletRequest request, @RequestParam(value = "username") String username, @RequestParam(value = "password") String password) {
System.out.println("登录:" + username + ":" + password);
HttpSession session = request.getSession();
if (null != session) {
session.setAttribute("SESSION_USERNAME", username);
return "success";
} else {
return "fail";
}
}
@ResponseBody
@RequestMapping("/sendToUser")
public String send(@RequestParam(value = "username") String username, @RequestParam(value = "info") String info) {
springWebSocketHandler.sendMessageToUser(username, new TextMessage(info));
System.out.println("发送至:" + username);
return "success";
}
@ResponseBody
@RequestMapping("/broadcast")
public String broadcast(@RequestParam(value = "info") String info) {
springWebSocketHandler.sendMessageToUsers(new TextMessage("广播消息:" + info));
System.out.println("广播成功");
return "success";
}
}
测试:
1.登录
打开http://localhost:8080/websocket/login?username=guest&password=123
2.连接
localhost:8080/index.html
3.推送消息到客户端
http://localhost:8080/websocket/sendToUser?username=river&info=%E4%BD%A0%E5%A5%BD
代码地址:https://github.com/HacahLT/webSocketDemo 直接拉取即可
参考或相关文章
https://blog.csdn.net/river66/article/details/102940323
https://www.ruanyifeng.com/blog/2017/05/websocket.html
|