websocket协议
HTTP协议是用在应用层的, 基于TCP协议的基础上,是单向的。 HTTP协议也需要建立三次握手才能够才能发送消息, HTTP连接分为短,长连接, 短连接每次请求都需要三次握手才能发送消息。长连接是在一定的期限内保持连接。保持TCP连接不断开。 客服端与服务端进行通信必须由客服端先发起, 客服端想要实时获取服务端信息就得不断发送长连接。
WebSocket实现了多路复用, 他是全双工通信。 服务端和客服端可以同时发送消息, 并且建立连接后服务端可以主动推送消息到客服端。 而且消息可以不用携带head部分信息。与http的长连接通信来说,这种方式,不仅能降低服务器的压力。而且信息当中也减少了部分多余的信息。
搭建说明
1、pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.jszt</groupId>
<artifactId>websocket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>websocket</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、配置文件
server.port=8080
spring.application.name=wesocket
# templates文件夹的路径
spring.thymeleaf.prefix=classpath:/templates/
# templates中的所有文件后缀名,如/templates/main.html
spring.thymeleaf.suffix=.html
3、WebSocketStompConfig
package com.jszt.websocket.config;
/**
* @author code
* @Date 2022/7/1 10:17
* Description 配置
* Version 1.0
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* websocket的配置
*/
@Configuration
public class WebSocketStompConfig{
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
return new ServerEndpointExporter();
}
}
4、service
package com.jszt.websocket.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author code
* @Date 2022/7/1 10:19
* Description 实现类
* Version 1.0
*/
@Slf4j
@Component
@ServerEndpoint("/websocket/{fromUser}/{toUser}")
public class WebSocketService {
/**
* 在线人数
*/
public static int onlineNumber = 0;
/**
* 在线名单
*/
private static Map<String,String> onlineMap = new HashMap<>();
/**
* 以用户的姓名和运维人员的姓名为key,WebSocket为对象保存起来
*/
private static Map<Map<String,String>, WebSocketService> clients = new ConcurrentHashMap<Map<String,String>, WebSocketService>();
/**
* 会话
*/
private Session session;
/**
* 发送者名称
*
*/
private String fromUser;
/**
* 接收者名称
*
*/
private String toUser;
/**
* 会话对象,去重
*/
private Map<String,String> map = new HashMap<>();
/**
* OnOpen 表示有浏览器链接过来的时候被调用
* OnClose 表示浏览器发出关闭请求的时候被调用
* OnMessage 表示浏览器发消息的时候被调用
* OnError 表示有错误发生,比如网络断开了等等
*/
/**
* 建立连接
*
* @param session
*/
@OnOpen
public void onOpen(@PathParam("fromUser") String fromUser,
@PathParam("toUser") String toUser,
Session session) {
//会话对象
map.put(fromUser,toUser);
//在线名单
onlineMap.put(fromUser,toUser);
onlineNumber++;
log.info("现在来连接的客户id:" + session.getId() + "发送者:" + fromUser + "接收者:" + toUser);
this.fromUser = fromUser;
this.toUser = toUser;
this.session = session;
log.info("有新连接加入! 当前在线人数" + onlineNumber);
try {
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
//先给所有人发送通知,说我上线了
Map<String, Object> map1 = new HashMap<>();
map1.put("messageType", 1);
map1.put("fromUser", fromUser);
sendMessageAll(JSON.toJSONString(map1), fromUser,toUser);
//把自己的信息加入到map当中去
clients.put(map, this);
//给自己发一条消息:告诉自己现在都有谁在线
Map<String, Object> map2 = new HashMap<>();
map2.put("messageType", 3);
//已经移除自己
Set<String> set = onlineMap.keySet();
log.info("在线名单"+set);
map2.put("onlineUsers", set);
sendMessageToSelf(JSON.toJSONString(map2), fromUser,toUser);
} catch (IOException e) {
log.info(fromUser + "上线的时候通知所有人发生了错误");
}
}
@OnError
public void onError(Session session, Throwable error) {
log.info("服务端发生了错误" + error.getMessage());
}
/**
* 连接关闭
*/
@OnClose
public void onClose() {
onlineNumber--;
clients.remove(map);
try {
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
Map<String, Object> map1 = new HashMap<>();
map1.put("messageType", 2);
map1.put("onlineUsers", clients.keySet());
map1.put("fromUser", fromUser);
sendMessageAll(JSON.toJSONString(map1), fromUser,toUser);
} catch (IOException e) {
log.info(fromUser + "下线的时候通知所有人发生了错误");
}
log.info("有连接关闭! 当前在线人数" + onlineNumber);
}
/**
* 收到客户端的消息
*
* @param message 消息
* @param session 会话
*/
@OnMessage
public void onMessage(String message, Session session) {
try {
log.info("来自客户端消息:" + message + "客户端的id是:" + session.getId());
JSONObject jsonObject = JSON.parseObject(message);
String textMessage = jsonObject.getString("message");
String fromusername = jsonObject.getString("fromUser");
String tousername = jsonObject.getString("to");
//如果不是发给所有,那么就发给某一个人
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
Map<String, Object> map1 = new HashMap<>();
map1.put("messageType", 4);
map1.put("textMessage", textMessage);
map1.put("fromusername", fromusername);
if (tousername.equals("All")) {
map1.put("tousername", "所有人");
sendMessageAll(JSON.toJSONString(map1), fromUser,tousername);
} else {
map1.put("tousername", tousername);
sendMessageTo(JSON.toJSONString(map1), fromUser,tousername);
}
} catch (Exception e) {
log.info("发生了错误了");
}
}
public void sendMessageTo(String message, String fromUser, String toUser) throws IOException {
log.info("--------发送的消息是---------"+message);
for (WebSocketService item : clients.values()) {
if (item.map.containsKey(toUser)&&item.map.get(toUser).equals(fromUser)) {
log.info("发送人:{}",fromUser);
log.info("转发送人:{}",toUser);
item.session.getAsyncRemote().sendText(message);
break;
}
}
}
public void sendMessageToSelf(String message, String fromUser, String toUser) throws IOException {
for (WebSocketService item : clients.values()) {
if (item.map.containsKey(fromUser)&&item.map.get(fromUser).equals(toUser)) {
log.info("发送人:{}",fromUser);
log.info("转发送人:{}",toUser);
item.session.getAsyncRemote().sendText(message);
break;
}
}
}
public void sendMessageAll(String message, String fromUser, String toUser) throws IOException {
for (WebSocketService item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineNumber;
}
}
6、controller
package com.jszt.websocket.controller;
/**
* @author code
* @Date 2022/7/1 10:31
* Description 控制层
* Version 1.0
*/
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Slf4j
@Controller
public class WebSocketController {
@RequestMapping("/websocket/{fromUser}/{toUser}")
public String webSocket(@PathVariable String fromUser,
@PathVariable String toUser,
Model model) {
try {
log.info("跳转到websocket的页面上");
model.addAttribute("fromUser", fromUser);
model.addAttribute("toUser", toUser);
return "websocket";
} catch (Exception e) {
log.info("跳转到websocket的页面上发生异常,异常信息是:" + e.getMessage());
return "error";
}
}
}
7、html
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<title>websocket</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
</head>
<body>
<div style="margin: auto;text-align: center">
<h1>简易版聊天</h1>
</div>
<br/>
<div style="margin: auto;text-align: center">
<select id="onLineUser">
<option>--所有--</option>
</select>
<input id="text" type="text"/>
<button onclick="send()">发送消息</button>
</div>
<br>
<div style="margin-right: 10px;text-align: right">
<button onclick="closeWebSocket()">关闭连接</button>
</div>
<hr/>
<div id="message" style="text-align: center;"></div>
<input type="text" th:value="${fromUser}" id="fromUser" style="display: none"/>
<input type="text" th:value="${toUser}" id="toUser" style="display: none"/>
</body>
<script type="text/javascript">
var webSocket;
var commWebSocket;
if ("WebSocket" in window) {
webSocket = new WebSocket("ws://172.30.59.76:8080/websocket/" + document.getElementById('fromUser').value + "/" + document.getElementById('toUser').value);
//连通之后的回调事件
webSocket.onopen = function () {
//webSocket.send( document.getElementById('username').value+"已经上线了");
console.log("已经连通了websocket");
setMessageInnerHTML("已经连通了websocket");
};
//接收后台服务端的消息
webSocket.onmessage = function (evt) {
var received_msg = evt.data;
console.log("数据已接收:" + received_msg);
var obj = JSON.parse(received_msg);
console.log("可以解析成json:" + obj.messageType);
//1代表上线 2代表下线 3代表在线名单 4代表普通消息
if (obj.messageType == 1) {
//把名称放入到selection当中供选择
var onlineName = obj.fromUser;
var option = "<option>" + onlineName + "</option>";
$("#onLineUser").append(option);
setMessageInnerHTML(onlineName + "上线了");
} else if (obj.messageType == 2) {
$("#onLineUser").empty();
var onlineName = obj.onlineUsers;
var offlineName = obj.fromUser;
var option = "<option>" + "--所有--" + "</option>";
for (var i = 0; i < onlineName.length; i++) {
if (!(onlineName[i] == document.getElementById('fromUser').value)) {
option += "<option>" + onlineName[i] + "</option>"
}
}
$("#onLineUser").append(option);
setMessageInnerHTML(offlineName + "下线了");
} else if (obj.messageType == 3) {
var onlineName = obj.onlineUsers;
console.log("获取的在线名单" + onlineName);
var option = null;
for (var i = 0; i < onlineName.length; i++) {
if (!(onlineName[i] == document.getElementById('fromUser').value)) {
option += "<option>" + onlineName[i] + "</option>"
}
}
$("#onLineUser").append(option);
console.log("获取了在线的名单" + onlineName.toString());
} else {
setMessageInnerHTML(obj.fromusername + "对" + obj.tousername + "说:" + obj.textMessage);
}
};
//连接关闭的回调事件
webSocket.onclose = function () {
console.log("连接已关闭...");
setMessageInnerHTML("连接已经关闭....");
};
} else {
// 浏览器不支持 WebSocket
alert("您的浏览器不支持 WebSocket!");
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
function closeWebSocket() {
//直接关闭websocket的连接
webSocket.close();
}
function send() {
var selectText = $("#onLineUser").find("option:selected").text();
if (selectText == "--所有--") {
selectText = "All";
} else {
setMessageInnerHTML(document.getElementById('fromUser').value + "对" + selectText + "说:" + $("#text").val());
}
var message = {
"message": document.getElementById('text').value,
"fromUser": document.getElementById('fromUser').value,
"to": selectText
};
webSocket.send(JSON.stringify(message));
$("#text").val("");
}
</script>
</html>
8、结果