demo链接:
https://download.csdn.net/download/qq_43560721/12558254
demo结构:
主要页面:
webSocket.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>即兴聊天</title>
</head>
<style>
ol,li{
margin: 0px;
padding: 0px;
}
</style>
<body>
<h3>欢迎来到:即兴聊天</h3>
<button onclick="openSocket()">开始聊天</button>
<p>【我】:<span class="my-user-id"></span>
<p>【好友】:<select name="user-list"></select>
<p>【消息】:
<div>
<input id="contentText" name="contentText" type="text" value="hello^-^">
<button onclick="sendMessage()">发送消息</button>
</div>
<div style="overflow:hidden;">
<div style="float: left;width: 50%;">
<p>【发送记录】:
<ol class="send-msg-ol" style="height: 200px;overflow:auto;font-size: 10px;">
</ol>
</div>
<div style="float: left;width: 50%;">
<p>【接收记录】:
<ol class="receive-msg-ol" style="height: 200px;overflow:auto;font-size: 10px;">
</ol>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
var socket;
var userId = new Date().getTime()
function openSocket() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
$(".my-user-id").html(userId)
// wss://sxj.easy.echosite.cn/webSocket/ ws://192.168.4.123:22599/webSocket/
var socketUrl = "wss://sxj.easy.echosite.cn/webSocket/" + userId;
console.log(socketUrl);
if (socket != null) {
socket.close();
socket = null;
}
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function () {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
toCmd(msg)
};
//关闭事件
socket.onclose = function () {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function () {
console.log("websocket发生了错误");
}
}
}
function sendMessage() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
// console.log("您的浏览器支持WebSocket");
var toUserId = $("select[name=user-list]").children("option:selected").attr("user-id");
var data = document.getElementById('contentText').value;
var sendObj = {
toUserId, data,
cmd: "log"
}
$(".send-msg-ol").append("<li>" + data + " " + new Date().toLocaleString() +
"</li>"
)
socket.send(JSON.stringify(sendObj));
}
}
/*解析返回数据的cmd*/
function toCmd(value) {
var {cmd, data} = JSON.parse(value.data)
switch (cmd) {
case "userList":
toUserList(data)
break
case "log":
toUserMessage(data)
break
}
}
/*渲染用户消息*/
function toUserMessage(data) {
var ol = $(".receive-msg-ol")
var li = "<li>" + data + " " + new Date().toLocaleString() +
"</li>"
ol.append(li)
}
/*渲染用户列表*/
function toUserList(data) {
$("select[name=user-list]").children().remove()
var op = ""
for (const i in data) {
var name = data[i] == userId ? "我自己" : data[i]
op += "<option user-id=" + data[i] + ">" + name + "</option>"
}
$("select[name=user-list]").append(op)
}
/*时间戳转字符串*/
Date.prototype.toLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate() + " " + this.getHours() + ':' + this.getMinutes() + ':' + this.getSeconds();
};
</script>
</html>
配置文件定义webSocket端口号
WebSocketConfig
package cn.xxs.springbootwbsocketdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Author xxs
* @Date 2020/4/24 15:41
*/
@Configuration
public class WebSocketConfig {
/**
* ServerEndpointExporter 作用
*
* 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
SendMess
package cn.xxs.springbootwbsocketdemo.pojo;
import java.util.List;
/**
* @Author xxs
* @Date 2020/6/27 22:10
*/
public class SendMess {
private String toUserId;
private String cmd;
private Object data;
public String getToUserId() {
return toUserId;
}
public void setToUserId(String toUserId) {
this.toUserId = toUserId;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
WebSocketServer
package cn.xxs.springbootwbsocketdemo.service;
import cn.xxs.springbootwbsocketdemo.pojo.SendMess;
import com.alibaba.fastjson.JSON;
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.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Author xxs
* @Date 2020/4/24 15:44
*/
@ServerEndpoint("/webSocket/{sid}")
@Component
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static AtomicInteger onlineNum = new AtomicInteger();
//concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
//发送消息
public void sendMessageByCmd(Session session, String cmd, Object obj) throws IOException {
SendMess mess = new SendMess();
mess.setCmd(cmd);
mess.setData(obj);
sendMessage(session, JSON.toJSONString(mess));
}
public void sendMessage(Session session, String message) throws IOException {
if(session != null){
synchronized (session) {
session.getBasicRemote().sendText(message);
}
}
}
//给指定用户发送信息
public void sendInfo(String userName, String message){
Session session = sessionPools.get(userName);
try {
sendMessage(session, message);
}catch (Exception e){
e.printStackTrace();
}
}
//建立连接成功调用
@OnOpen
public void onOpen(Session session, @PathParam(value = "sid") String userName){
sessionPools.put(userName, session);
addOnlineCount();
System.out.println(userName + "加入webSocket!当前人数为" + onlineNum);
List<String> userIds = new ArrayList();
Enumeration<String> keys = sessionPools.keys();
while(keys.hasMoreElements()){
String value = keys.nextElement();//调用nextElement方法获得元素
userIds.add(value);
}
System.out.println("=============当前用户:" + userIds.toString());//打印当前参与聊天人数
for(Session s:sessionPools.values()){
try {
sendMessageByCmd(s,"userList",userIds);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//关闭连接时调用
@OnClose
public void onClose(@PathParam(value = "sid") String userName){
sessionPools.remove(userName);
subOnlineCount();
System.out.println(userName + "断开webSocket连接!当前人数为" + onlineNum);
}
//收到客户端信息
@OnMessage
public void onMessage(String message) throws IOException{
SendMess u = JSON.parseObject(message, SendMess.class);
System.out.println("客户端:" + message + ",已收到");
String toUserId = u.getToUserId();
Session session = sessionPools.get(toUserId);
//只发给指定人
if(session!=null){
try {
sendMessageByCmd(session,u.getCmd(),u.getData());
} catch(Exception e){
e.printStackTrace();
}
}
}
//错误时调用
@OnError
public void onError(Session session, Throwable throwable){
System.out.println("发生错误");
throwable.printStackTrace();
}
public static void addOnlineCount(){
onlineNum.incrementAndGet();
}
public static void subOnlineCount() {
onlineNum.decrementAndGet();
}
}
演示:
我的界面:
好友界面: