定义
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
为什么要用webSocket
很多网站为了实现推送技术,所用的技术都是轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。
而比较新的技术去做轮询的效果是Comet。这种技术虽然可以双向通信,但依然需要反复发出请求。而且在Comet中,普遍采用的长链接,也会消耗服务器资源。
在这种情况下,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯
原理
网上关于webScoket的原理的解释很多,这里放一个地址,大家有时间的可以看一下,本文主要描述怎么实现webSocket。
地址:https://www.zhihu.com/question/20215561
webSocke使用
**1、新建springboot项目,引入关联jar包**
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
**2、配置类以及html创建**
package com.example.websocket.websocker;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
* @author admin
*/
@Configuration
public class WebSocketConfig {
/**
* ServerEndpointExporter 作用
* 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.example.websocket.websocker;
import com.example.websocket.message.RequestMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
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.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Admin
*/
@ServerEndpoint("/webSocket/{userId}")
@Component
public class WebSocketServer {
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
private static AtomicInteger onlineNum = new AtomicInteger();
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
*/
private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
/**
* 发送消息
*/
public void sendMessage(Session session, String message) throws IOException {
if(session != null){
synchronized (session) {
System.out.println("发送数据:" + message);
session.getBasicRemote().sendText(message);
}
}
}
/**
* 建立连接成功调用
* @param session
* @param userId
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId") String userId){
sessionPools.put(userId, session);
addOnlineCount();
System.out.println(userId + "加入webSocket!当前人数为" + onlineNum);
try {
sendMessage(session, "用户" + userId + "加入连接!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 关闭连接时调用
*/
@OnClose
public void onClose(@PathParam(value = "userId") String userId){
sessionPools.remove(userId);
subOnlineCount();
System.out.println(userId + "断开webSocket连接!当前人数为" + onlineNum);
}
/**
* 收到客户端信息
*/
@OnMessage
public void onMessage(String message) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
RequestMessage requestMessage = objectMapper.readValue(message, RequestMessage.class);
//判断接收者ID是否为空,不是空的话,默认发给所有人
if (StringUtils.isNotBlank(requestMessage.getReceiveId())){
Session session = sessionPools.get(requestMessage.getReceiveId());
try {
sendMessage(session, requestMessage.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}else{
for (Session session: sessionPools.values()) {
try {
sendMessage(session, requestMessage.getMessage());
} catch(IOException e){
e.printStackTrace();
continue;
}
}
}
}
/**
* 错误时调用
*/
@OnError
public void onError(Session session, Throwable throwable){
System.out.println("webSocket连接出错牌");
throwable.printStackTrace();
}
/**
* 当前连接数+1
*/
public static void addOnlineCount(){ onlineNum.incrementAndGet(); }
/**
* 当前连接数-1
*/
public static void subOnlineCount() {
onlineNum.decrementAndGet();
}
}
package com.example.websocket.message;
import lombok.Data;
/**
* @author Admin
*/
@Data
public class RequestMessage {
/**
* 接收者ID
*/
private String receiveId;
/**
* 消息内容
*/
private String message;
}
package com.example.websocket.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* @author Admin
*/
@Controller
public class SocketController {
@GetMapping("/webSocket")
public String socket() {
return "/webSocket";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<h1>webSocket</h1>
<div>发送者ID <input id="userId" name="userId" type="text"></div>
<br>
<div>接收者ID <input id="receiveId" name="receiveId" type="text"></div>
<br>
<div>启动连接  <button onclick="openSocket()">开启socket</button></div>
<br><br>
<div>消息内容 <input id="message" name="message" type="text"></div>
<br>
<div>发送消息 <button onclick="sendMessage()">发送消息</button></div>
<br>
<div>接收消息如下</div>
<div><p id="receiveText"></p></div>
</body>
<script>
let socket;
function openSocket() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
let userId = document.getElementById('userId').value;
let socketUrl = "ws://127.0.0.1:8080/webSocket/"+userId;
if(socket != null){
socket.close();
socket = null;
}
socket = new WebSocket(socketUrl);
//webSocket打开
socket.onopen = function() {
console.log("websocket已打开");
};
//接收webSocket消息事件
socket.onmessage = function(msg) {
document.getElementById('receiveText').innerHTML = msg.data;
};
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
}
}
function sendMessage() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else {
let userId = document.getElementById('receiveId').value;
let message = document.getElementById('message').value;
let object = {};
object['receiveId'] = userId;
object['message'] = message;
socket.send(JSON.stringify(object));
}
}
</script>
</html>
目录结构如下
社区新人,如果对大家有用的话,麻烦给点个赞,万分感谢