前言
WebSocket
是什么?
WebSocket
是一种网络通信协议,是 HTML5
开始提供的一种在单个 TCP
连接上进行全双工通讯的协议
- 为什么需要
WebSocket
?
我们都知道:HTTP
协议是一种无状态的、无连接的、单向的应用层协议。它采用了请求/响应模型。通信请求只能由客户端发起,服务端对请求做出应答处理,这种通信模型有一个弊端:HTTP
协议无法实现服务器主动向客户端发起消息(当然我们可以建立一个长连接来实现双向的交互),这种单向请求的特点,注定了如果服务器有连续的状态变化,客户端要获知就非常麻烦。大多数 Web
应用程序将通过频繁的异步 JavaScript
和 XML
(AJAX
)请求实现长轮询。轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP
连接始终打开);而WebSocket
连接允许客户端和服务器之间进行全双工通信,以便任一方都可以通过建立的连接将数据推送到另一端。WebSocket
只需要建立一次连接,就可以一直保持连接状态。这相比于轮询方式的不停建立连接显然效率要大大提高。
WebSocket
如何工作?
Web 浏览器和服务器都必须实现 WebSockets 协议来建立和维护连接。由于 WebSockets 连接长期存在,与典型的 HTTP 连接不同,对服务器有重要的影响。基于多线程或多进程的服务器无法适用于 WebSockets,因为它旨在打开连接,尽可能快地处理请求,然后关闭连接。任何实际的 WebSockets 服务器端实现都需要一个异步服务器。
WebSocket 客户端
let Socket = new WebSocket(url, [protocol] );
属性 |
描述 |
Socket.readyState |
只读属性 readyState 表示连接状态,可以是以下值:0: 表示连接尚未建立。1 : 表示连接已建立,可以进行通信。2 : 表示连接正在进行关闭。3 : 表示连接已经关闭或者连接不能打开 |
Socket.bufferedAmount |
只读属性 bufferedAmount 已被 send() 放入正在队列中等待传输,但是还没有发出的 UTF-8 文本字节数 |
事件 |
事件处理程序 |
描述 |
open |
Socket.onopen |
连接建立时触发 |
message |
Socket.onmessage |
客户端接收服务端数据时触发 |
error |
Socket.onerror |
通信发生错误时触发 |
close |
Socket.onclose |
连接关闭时触发 |
方法 |
描述 |
Socket.send() |
使用连接发送数据 |
Socket.close() |
关闭连接 |
let ws = new WebSocket('ws://localhost:8080/webSocket');
ws.onopen = function() {
ws.send('发送数据');
};
ws.onmessage = function(evt) {
var received_msg = evt.data;
};
ws.onclose = function() {
alert('连接已关闭...');
};
WebSocket 服务器端
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
@Configuration
public class WebSocketConfig {
@Bean
ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
@Slf4j
@Component
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {
private static AtomicInteger onlineNum = new AtomicInteger();
private static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
public void sendMsg(Session session,String msg) throws IOException {
if(null != session){
synchronized (session){
log.info("发送消息:客户端:{},消息:{}",session.getId(),msg);
session.getBasicRemote().sendText(msg);
}
}
}
public void sendMsgToUser(String userName,String msg) throws IOException {
Session session = sessions.get(userName);
sendMsg(session,msg);
}
@OnOpen
public void onOpen(Session session,@PathParam("sid") String userName) throws IOException {
sessions.put(userName,session);
addOnlineCount();
log.info("欢迎{}登录!",userName);
sendMsgToUser(userName,"欢迎" + userName + "登录!");
}
@OnClose
public void onClose(@PathParam("sid") String userName){
sessions.remove(userName);
subOnlineCount();
log.info("{}断开连接,当前在线客户数{}!",userName,onlineNum);
}
@OnMessage
public void onMsg(String msg){
msg = "客户端:" + msg + ",已收到";
log.info(msg);
for (Session session : sessions.values()) {
try {
sendMsg(session,msg);
} catch (IOException e) {
log.error("客户端:{}接收消息异常!",session.getId());
continue;
}
}
}
public static void addOnlineCount(){
onlineNum.incrementAndGet();
}
public static void subOnlineCount(){
onlineNum.decrementAndGet();
}
}
即时聊天室Demo
- 整体项目结构
- 项目依赖
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
dependencies>
@Configuration
public class WebSocketConfig {
@Bean
ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
@Slf4j
@Component
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {
private static AtomicInteger onlineNum = new AtomicInteger();
private static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
public void sendMsg(Session session,String msg) throws IOException {
if(null != session){
synchronized (session){
log.info("发送消息:客户端:{},消息:{}",session.getId(),msg);
session.getBasicRemote().sendText(msg);
}
}
}
public void sendMsgToUser(String userName,String msg) throws IOException {
Session session = sessions.get(userName);
sendMsg(session,msg);
}
@OnOpen
public void onOpen(Session session,@PathParam("sid") String userName) throws IOException {
sessions.put(userName,session);
addOnlineCount();
log.info("欢迎{}登录!",userName);
sendMsgToUser(userName,"欢迎" + userName + "登录!");
}
@OnClose
public void onClose(@PathParam("sid") String userName){
sessions.remove(userName);
subOnlineCount();
log.info("{}断开连接,当前在线客户数{}!",userName,onlineNum);
}
@OnMessage
public void onMsg(String msg){
msg = "客户端:" + msg + ",已收到";
log.info(msg);
for (Session session : sessions.values()) {
try {
sendMsg(session,msg);
} catch (IOException e) {
log.error("客户端:{}接收消息异常!",session.getId());
continue;
}
}
}
public static void addOnlineCount(){
onlineNum.incrementAndGet();
}
public static void subOnlineCount(){
onlineNum.decrementAndGet();
}
}
- 业务接口
SocketController.java
@Controller
public class SocketController {
@Autowired
private WebSocketServer webService;
@RequestMapping("/index")
public String index() {
return "index";
}
@GetMapping("/webSocket2")
public String socket() {
return "webSocket";
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h3>hello socketh3>
<p>【userId】:<div><input id="userId" name="userId" type="text" value="10">div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="20">div>
<p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="hello websocket">div>
<p>操作:<div><a onclick="openSocket()">开启socketa>div>
<p>【操作】:<div><a onclick="sendMsg()">发送消息a>div>
body>
<script>
let socket;
<!-- 建立连接 -->
function openSocket(){
if(typeof (WebSocket) == "undefined"){
console.log("当前浏览器不支持WebSocket");
}else{
console.log("当前浏览器支持WebSocket");
let sid = document.getElementById('userId').value;
let socketUrl = "ws://127.0.0.1:8088/websocket/" + sid;
if(socket != null){
socket.close();
socket = null;
}
socket = new WebSocket(socketUrl);
socket.onopen = function () {
console.log("WebSocket已连接");
}
socket.onmessage = function (msg) {
let serverMsg = "服务器:" + msg.data;
console.log(serverMsg);
}
socket.onclose = function () {
console.log("WebSocket已断开");
}
socket.onerror = function () {
console.log("WebSocket未知错误");
}
}
}
<!-- 发送消息 -->
function sendMsg(){
if(typeof (WebSocket) == "undefined"){
console.log("当前浏览器不支持WebSocket");
}else{
console.log("当前浏览器支持WebSocket");
let toUserId = document.getElementById('toUserId').value;
let msgContent = document.getElementById('contentText').value;
let msg = '{"toUserId":"'+toUserId+'","msgContent":"'+msgContent+'"}';
socket.send(msg);
}
}
script>
html>