不废话,上代码,贴了就好使!
java端代码
import com.alibaba.fastjson.JSON;
import com.zmj.digitalworkshop.panel.dip.angle.entity.Message;
import io.swagger.annotations.ApiOperation;
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.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@Component
@ServerEndpoint("/webSocket/{username}")
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 = "username") String userName) throws IOException, InterruptedException {
sessionPools.put(userName, session);
addOnlineCount();
System.out.println(userName + "加入webSocket!当前人数为" + onlineNum);
}
@OnClose
@ApiOperation(value = "获取当前在线用户数量及列表", notes = "获取当前在线用户数量及列表", httpMethod = "WS")
public void onClose(@PathParam(value = "username") String userName) throws IOException {
sessionPools.remove(userName);
subOnlineCount();
System.out.println(userName + "断开webSocket连接!当前人数为" + onlineNum);
}
public static void sendInfo(String userName, String message){
Session session = sessionPools.get(userName);
try {
sendMessage(session, message);
}catch (Exception e){
e.printStackTrace();
}
}
public void broadcast(String message){
for (Session session: sessionPools.values()) {
try {
sendMessage(session, message);
} catch(Exception e){
e.printStackTrace();
continue;
}
}
}
public static void sendMessage(Session session, String message) throws IOException {
if(session != null){
synchronized (session) {
System.out.println("发送数据:" + message);
session.getBasicRemote().sendText(message);
}
}
}
@OnMessage
public void onMessage(String message) throws IOException{
System.out.println("server get" + message);
Message msg=JSON.parseObject(message, Message.class);
msg.setDate(new Date());
if (msg.getType().equals("-1")) {
broadcast(JSON.toJSONString(msg,true));
} else {
sendInfo(msg.getType(), JSON.toJSONString(msg,true));
}
}
@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();}
public static AtomicInteger getOnlineNumber() {return onlineNum;}
public static ConcurrentHashMap<String, Session> getSessionPools() {return sessionPools;}
}
前端代码
随便写了点大概意思就是这 TOM就是要链接的用户名称
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
getWS()
function getWS(){
const ws= new WebSocket('ws://127.0.0.1:8080/webSocket/TOM')
ws.onopen = function(){
console.log('建立链接')
}
}
</script>
</body>
</html>
要看浏览器 websocket 的数据的话,如下: 谷歌,F12,然后点 WS,就能看到 webSocket 的一些消息了 别看我的报红了,因为我懒,不想开项目,它连不上
要是写的还行的话,给我点动力点个赞吧 有什么问题当前页面请留言。
|