WebScoketServer
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.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@ServerEndpoint("/websocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {
private static AtomicInteger onlineNum = new AtomicInteger();
private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam(value = "sid") String userName) {
sessionPools.put(userName, session);
addOnlineCount();
System.out.println(userName + "加入webSocket" + onlineNum);
String s = "欢迎" + userName + "加入链接";
ByteBuffer byteBuffer = ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8));
sendMessage(session, byteBuffer);
}
@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, Session session) {
System.out.println(message);
}
@OnMessage
public void onMessage(ByteBuffer byteBuffer, Session session) {
CharBuffer charBuffer;
Charset charset = StandardCharsets.UTF_8;
CharsetDecoder decoder = charset.newDecoder();
try {
charBuffer = decoder.decode(byteBuffer);
System.out.println("收到信息:" + charBuffer.toString());
} catch (CharacterCodingException e) {
e.printStackTrace();
}
String resultStr = "{message:\" 收到消息 \"}";
byte[] resultBytes = resultStr.getBytes(StandardCharsets.UTF_8);
ByteBuffer wrap = ByteBuffer.wrap(resultBytes);
sendMessage(session, wrap);
}
@OnError
public void onError(Throwable throwable, @PathParam("sid") String userName) {
System.out.println("发生错误");
throwable.printStackTrace();
try {
sessionPools.get(userName).close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(Session session, String message) {
if (session != null) {
synchronized(session) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
String warnMessage = "传送字符串消息错误";
log.warn("websocketServer: {},{}", warnMessage, e);
}
}
}
}
public void sendMessage(Session session, ByteBuffer byteBuffer) {
if (session != null) {
synchronized (session) {
try {
session.getBasicRemote().sendBinary(byteBuffer);
} catch (IOException e) {
String warnMessage = "传送字节数组消息错误";
log.warn("websocketServer: {},{}", warnMessage, e);
}
}
}
}
public void sendInfo(String userName, String message) {
Session session = sessionPools.get(userName);
sendMessage(session, message);
}
public void sendInfo(String userName, ByteBuffer byteBuffer) {
Session session = sessionPools.get(userName);
sendMessage(session, byteBuffer);
}
public static void addOnlineCount() {
onlineNum.incrementAndGet();
}
public static void subOnlineCount() {
onlineNum.decrementAndGet();
}
}
## H5界面
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"> </script>
</head>
<body>
<h3>基于web socket 点对点通讯</h3>
【当前用户ID】:<input id="userId" name="userId" type="text" value="10"><br><br>
【对方用户ID】:<input id="toUserId" name="toUserId" type="text" value="20"><br> <br>
【发送信息】: <input id="sendMsg" name="sendMsg" type="text" value="hello websocket"><br><br>
【接收信息】: <span id="receiveMsg" style="color: #800080"></span><br><br>
<button id="openBtn">开启socket</button><br><br>
<button id="sendBtn">发送消息</button><br><br>
</body>
<script>
let socket;
$("#openBtn").click(function() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
var userId = $('#userId').val();
var socketUrl="ws://localhost:22598/websocket/10?uniqueId=sip-1-1534847965.97644&enterpriseId=7000101&cno=10001";
console.log(socketUrl);
if(socket!=null) {
socket.close();
socket=null;
}
socket = new WebSocket(socketUrl);
socket.onopen = function() {
console.log("websocket已打开");
}
socket.onclose = function() {
console.log("websocket已关闭");
};
socket.onerror = function() {
console.log("websocket发生了错误");
};
socket.onmessage = function(msg) {
console.log(msg.data);
$("#receiveMsg").html(msg.data);
};
}
});
$("#sendBtn").click(function () {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
var toUserId = $("#toUserId").val();
var sendMsg = $("#sendMsg").val();
var o = {};
o.toUserId = toUserId;
o.sendMsg = sendMsg;
var msg = JSON.stringify(o);
console.log(msg);
socket.send(msg);
}
});
</script>
</html>