WebSocket
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
与Ajax 轮询相比HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。
为什么WebSocket连接可以实现全双工通信而HTTP连接不行呢?实际上HTTP协议是建立在TCP协议之上的,TCP协议本身就实现了全双工通信,但是HTTP协议的请求-应答机制限制了全双工通信。WebSocket连接建立以后,其实只是简单规定了一下:连接建立起来后就不使用HTTP协议了,直接互相发数据
WebSocket协议
WebSocket并不是全新的协议,而是利用了HTTP协议来建立连接。我们来看看WebSocket连接是如何创建的。
首先,WebSocket连接必须由浏览器发起,因为请求协议是一个标准的HTTP请求,格式如下:
以下是需要注意的:
GET请求的地址是以 ws:// 开头的地址;
请求头Upgrade: websocket和Connection: Upgrade表示这个连接将要被转换为WebSocket连接;
Sec-WebSocket-Key是用于标识这个连接,并非用于加密数据;
Sec-WebSocket-Version指定了WebSocket的协议版本。
服务器接受请求后会返回,如下响应
响应状态码101表示本次连接的HTTP协议即将被更改,更改后的协议就是Upgrade: websocket指定的WebSocket协议
SpringBoot使用WebSocket实现简单的聊天功能
添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
启动WebSocket
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
WebSocket实现类,能够接受信息和发送信息
@Slf4j
@Component
@ServerEndpoint("/websocket/{userName}")
public class WebSocket {
/**
* 在线人数
*/
public static int onlineNumber = 0;
/**
* 以用户的姓名为key,WebSocket为对象保存起来
*/
private static Map<String,WebSocket> clients = new ConcurrentHashMap<>();
/**
* 会话
*/
private Session session;
/**
* 用户名称
*/
private String userName;
/**
* 建立连接
* @param userName
* @param session
*/
@OnOpen
public void onOpen(@PathParam("userName")String userName,Session session){
onlineNumber++;
log.info("现在来连接的客户id: "+session.getId()+" 用户名: "+userName);
this.userName = userName;
this.session = session;
log.info("有新连接加入!当前在线人数 "+onlineNumber);
try {
//告诉所有人,userName上线了
Map<String,Object> map = new HashMap<>();
map.put("messageType",1 );
map.put("userName",userName );
sendMessageAll(JSON.toJSONString(map),userName);
//把userName的信息加入到clients中
clients.put(userName,this );
//告诉userName现在都有谁在线
Map<String,Object> map2 = new HashMap<>();
map2.put("messageType",3 );
Set<String> set = clients.keySet();
map2.put("onlineUsers",set );
sendMessageTo(JSON.toJSONString(map2),userName);
}catch (Exception e){
log.info(userName+"上线的时候通知所有人发生了错误");
}
}
/**
* 发生错误
* @param session
* @param error
*/
@OnError
public void onError(Session session,Throwable error){
log.info("服务端发生了错误: "+error.getMessage());
}
/**
* 关闭连接
*/
@OnClose
public void onClose(){
onlineNumber--;
clients.remove(userName);
try {
Map<String,Object> map = new HashMap<>();
map.put("messageType",2 );
map.put("onlineUsers",clients.keySet() );
map.put("userName",userName );
sendMessageAll(JSON.toJSONString(map),userName );
}catch (Exception e){
log.info(userName+"下线的时候通知所有人发生了错误");
}
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("userName");
String toUserName = jsonObject.getString("to");
Map<String,Object> map = new HashMap<>();
map.put("messageType",4 );
map.put("textMessage",textMessage );
map.put("fromUserName",fromUserName );
if(toUserName.equals("All")){
map.put("toUserName","所有人" );
sendMessageAll(JSON.toJSONString(map),fromUserName );
}else{
map.put("toUserName",toUserName );
sendMessageTo(JSON.toJSONString(map),toUserName );
}
}catch (Exception e){
log.info("发生了错误");
}
}
/**
* 发送消息给指定的userName
* @param message
* @param toUserName
*/
private void sendMessageTo(String message, String toUserName) {
for (WebSocket webSocket : clients.values()) {
if(webSocket.userName.equals(toUserName)){
webSocket.session.getAsyncRemote().sendText(message);
break;
}
}
}
/**发送消息给所有人
*
* @param message
* @param fromUserName
*/
private void sendMessageAll(String message, String fromUserName) {
for (WebSocket webSocket : clients.values()) {
webSocket.session.getAsyncRemote().sendText(message);
}
}
/**
* 返回在线人数
* @return
*/
public static synchronized int getOnlineNumber(){
return onlineNumber;
}
}
WebSocketController
@Slf4j
@Controller
public class WebSocketController {
@RequestMapping("/websocket/{name}")
public String webSocket(@PathVariable String name, Model model){
try {
log.info("跳转到webSocket的页面上");
model.addAttribute("userName",name );
return "websocket";
}catch (Exception e){
log.info("跳转到websocket的页面上发送异常: "+e.getMessage());
return "error";
}
}
}
页面
<!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>Welcome to websocket</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="${userName}" id="userName" style="display: none"/>
</body>
<script type="text/javascript">
var webSocket;
if ("WebSocket" in window) {
webSocket = new WebSocket("ws://localhost:8080/websocket/" + document.getElementById('userName').value);
//连通之后的回调事件
webSocket.onopen = function () {
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.userName;
var option = "<option>" + onlineName + "</option>";
$("#onLineUser").append(option);
setMessageInnerHTML(onlineName + "上线了");
} else if (obj.messageType == 2) {
$("#onLineUser").empty();
var onlineName = obj.onlineUsers;
var offlineName = obj.userName;
var option = "<option>" + "--所有--" + "</option>";
for (var i = 0; i < onlineName.length; i++) {
if (!(onlineName[i] == document.getElementById('userName').value)) {
option += "<option>" + onlineName[i] + "</option>"
}
}
$("#onLineUser").append(option);
setMessageInnerHTML(offlineName + "下线了");
} else if (obj.messageType == 3) {
var onlineName = obj.onlineUsers;
var option = null;
for (var i = 0; i < onlineName.length; i++) {
if (!(onlineName[i] == document.getElementById('userName').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('userName').value + "对" + selectText + "说:" + $("#text").val());
}
var message = {
"message": document.getElementById('text').value,
"userName": document.getElementById('userName').value,
"to": selectText
};
webSocket.send(JSON.stringify(message));
$("#text").val("");
}
</script>
</html>
效果
参考博客:
springboot整合websocket实现聊天系统
Spring Boot整合websocket实现群聊,点对点聊天
完整的代码在我的GitHub