赞
踩
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
属性返回实例对象的当前状态,共有四种。
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 实现有以下三种。
使用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;
// 获取session时,如果没有则返回null
HttpSession session = servletRequest.getServletRequest().getSession(false);
if (session != null) {
// 在登录时保存的用户名
String userName = (String) session.getAttribute("SESSION_USERNAME");
if (userName != null) {
// 放入attributes中,可以在处理器的WebSocketSession中取出
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 {
/**
* 存储用户id和其对应的session
*/
private static final Map<String, WebSocketSession> users = new HashMap<>();
/**
* 用户名key值
*/
private static final String USER_ID = "WEBSOCKET_USERID";
/**
* 连接建立后触发
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) {
System.out.println("成功建立websocket连接!");
// 取出在拦截器中存储的username
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;
/*GET请求开放用于测试,最好只允许POST请求*/
@Controller
@RequestMapping(value = "/websocket", method = {RequestMethod.POST, RequestMethod.GET})
public class WebSocketController {
@Autowired
SpringWebSocketHandler springWebSocketHandler;
/**
* 登录将username放入session中,然后在拦截器HandshakeInterceptor中取出
*/
@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
代码地址:gitee
https://blog.csdn.net/river66/article/details/102940323
https://www.ruanyifeng.com/blog/2017/05/websocket.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。