pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocket代码
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.concurrent.ConcurrentHashMap;
@SuppressWarnings("all")
@ServerEndpoint(value = "/webSockets/{param}")
@Component
public class WebSocket {
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
public static int onlineCount = 0;
// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static ConcurrentHashMap<String, WebSocket> webSocketSet =
new ConcurrentHashMap<String, WebSocket>();
// 给当前用户一个全局的标识
public String userno = "";
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(
@PathParam(value = "param") String param, Session session, EndpointConfig config) {
userno = param;
this.session = session;
webSocketSet.put(userno, this); // 加入map中
addOnlineCount(); // 在线数加1
System.err.println("新的用户链接,当前在线用户人数:" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); // 从set中删除
subOnlineCount(); // 在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
}
/**
* 给指定的人发送消息
*
* @param message
*/
public String sendToUser(String key, String message) {
try {
if (webSocketSet.get(key) != null) {
webSocketSet.get(key).sendMessage(message);
return "0";
} else {
return "1";
}
} catch (IOException e) {
e.printStackTrace();
return "500";
}
}
/**
* 给所有人发消息
*
* @param message
*/
public void sendAll(String message) {
// 遍历HashMap
for (String key : webSocketSet.keySet()) {
try {
// 判断接收用户是否是当前发消息的用户
if (!userno.equals(key)) {
webSocketSet.get(key).sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
// this.session.getAsyncRemote().sendText(message);
}
}
如果用SpringBoot内置Tomcat启动 需要加一个类WebSocketConfig
@SuppressWarnings("all")
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
调用的时候:
@RequestMapping(
value = "/v1.0/userPush",
method = RequestMethod.POST,
produces = {"application/json;charset=UTF-8", "text/html"})
public void userPush(String key, String msg) {
new WebSocket.sendToUser(key, msg);
}
前端JS:
//获取网页缓存.
// var push = localStorage.getItem("push");
var push = '123';
var websocket = null;
//判断当前浏览器是否支持WebSocket
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
if ('WebSocket' in window) {
var wsUrl = 'ws://192.168.10.119/webSockets/'+push;
websocket = new WebSocket(wsUrl);
}
else {
setMessageInnerHTML('当前浏览器 不支持WebSocket');
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("链接建立")
}
//接收到消息的回调方法,此处添加处理接收消息方法,当前是将接收到的信息显示在网页上
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("连接关闭,如需登录请刷新页面。");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
// 将消息显示在网页上,如果不需要显示在网页上,则不调用该方法
function setMessageInnerHTML(innerHTML) {
document.write(innerHTML);
console.log(innerHTML);
}