5,655
社区成员
发帖
与我相关
我的任务
分享
@ServerEndpoint(value = "/websocket")
@Component
public class WSServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WSServer> webSocketSet = new CopyOnWriteArraySet<WSServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
try {
// sendMessage(CommonConstant.CURRENT_WANGING_NUMBER.toString());
sendMessage("123456");
} catch (IOException e) {
System.out.println("IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//群发消息
for (WSServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
var socket;
if(typeof(WebSocket) == "undefined") {
alert("您的浏览器不支持WebSocket");
return;
}alert("您的浏览器支持WebSocket");
$("#btnConnection").click(function() {
//实现化WebSocket对象,指定要连接的服务器地址与端口
//"ws://127.0.0.1:8087/WebSocketServer/ws/张三"
// ws://localhost:8084/websocket 这行和下面的哪行同样是404
socket = new WebSocket("ws://localhost:9094");
//打开事件
socket.onopen = function() {
alert("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
alert(msg.data);
};
//关闭事件
socket.onclose = function() {
alert("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("发生了错误");
}
});