webSocket学习备忘录
服务端:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/websocket/{userno}")
public class SocketConteller {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static ConcurrentHashMap<String, SocketConteller> webSocketSet = new ConcurrentHashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session WebSocketsession;
//当前发消息的人员编号
private String userno = "";
/**
* 连接建立成功调用的方法
* <p>
*/
@OnOpen
public void onOpen(@PathParam(value = "userno") String param, Session WebSocketsession, EndpointConfig config) {
// System.out.println(param);
userno = param;//接收到发送消息的人员编号
this.WebSocketsession = WebSocketsession;
webSocketSet.put(param, this);//加入map中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
systemSend();
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!userno.equals("")) {
webSocketSet.remove(userno); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
systemSend();
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@SuppressWarnings("unused")
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
// session.get
//群发消息
Map mess = JSONObject.parseObject(message, Map.class);
String toUser = (String) mess.get("toUser");
if (toUser.equals("")) {//判断有没有接收人,没有就是全体消息
sendAll(mess);
} else {
//给指定的人发消息
sendToUser(mess);
}
}
/**
* 给指定的人发送消息
*
* @param message
*/
public void sendToUser(Map message) {
String toUser = (String) message.get("toUser");
String content = (String) message.get("content");
String toTime = (String) message.get("toTime");
message.put("messType","one");
message.put("static",1);
String mess= JSON.toJSONString(message);
try {
if (webSocketSet.get(toUser) != null) {
webSocketSet.get(toUser).sendMessage(mess);
} else {
System.out.println("当前用户不在线");
message.put("static",0);
message.put("systemMsg","用户不在线");
mess= JSON.toJSONString(message);
webSocketSet.get(userno).sendMessage(mess);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 给所有人发消息
*
* @param message
*/
private void sendAll(Map message) {
//遍历HashMap
message.put("messType","all");
String mess= JSON.toJSONString(message);
for (String key : webSocketSet.keySet()) {
try {
//判断接收用户是否是当前发消息的用户
if (!userno.equals(key)) {
webSocketSet.get(key).sendMessage( mess);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private synchronized void systemSend() {
for (String key : webSocketSet.keySet()) {
try {
String mess=JSON.toJSONString(new HashMap<String,Object>(){{
put("messType","system");
put("peopleSum",getOnlineCount());
}});
webSocketSet.get(key). sendMessage(mess);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取当前时间
*
* @return
*/
private String getNowTime() {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
return time;
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
*
* @param message
* @throws IOException
*/
public synchronized void sendMessage( String message) throws IOException {
WebSocketsession.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
SocketConteller.onlineCount++;
}
public static synchronized void subOnlineCount() {
SocketConteller.onlineCount--;
}
}
客户端:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Java后端WebSocket实现</title>
<meta charset="UTF-8">
<script src="static/webSocket.js"></script>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<!--userno:发送消息人的编号-->
发送人:
<div id="userno">1</div>
接收人:<input type="text" id="usernoto"><br>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<button onclick="openWebSocket()">打开WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>
<script>
var websocket = null;
var userno = null;
function openWebSocket(i){
userno = document.getElementById('userno').innerHTML
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8081/websocket/" + userno);
} else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
}
</script>
</html>
公共js:
//将消息显示在网页上
function setMessageInnerHTML(sendMessage) {
document.getElementById('message').innerHTML += sendMessage + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;//要发送的消息内容
var now = getNowFormatDate();//获取当前时间
document.getElementById('message').innerHTML += (now + "发送人:" + userno + '' + "---" + message) + '<br/>';
document.getElementById('message').style.color = "red";
var ToSendUserno = document.getElementById('usernoto').value; //接收人编号:4567
// message = message + "|" + ToSendUserno//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
let mess = {
toUser: ToSendUserno,
content: message,
toTime: this.getNowFormatDate()
}
message = JSON.stringify(mess)
websocket.send(message);
}
//获取当前时间
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}
服务端@ServerEndpoint注解的值是即时通讯的链接
拦截器内需要添加
@Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }
引入的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.3.1.RELEASE</version> </dependency>
最后说一句,多个客户端的差异只是<div id="userno">1</div>的值发生了改变