2021-10-21-前后端分离:java websocket实时通讯【已经在项目中使用】

2021-10-21-前后端分离:java websocket实时通讯【已经在项目中使用】,第1张

2021-10-21-前后端分离:java websocket实时通讯【已经在项目中使用】

前后端分离:java websocket实时通讯【已经在项目中使用】

第一个java类:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {

@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

第二个java类:
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@ServerEndpoint(value = “/websocket”)
@Component
public class WebSocketServer {


private static AtomicInteger onlineCount = new AtomicInteger(0);


public static Map clients = new ConcurrentHashMap<>();


@OnOpen
public void onOpen(Session session) {
onlineCount.incrementAndGet(); // 在线数加1
clients.put(session.getId(), session);
log.info(“有新连接加入:{},当前在线人数为:{}”, session.getId(), onlineCount.get());
sendMessage(session.getId(),session);
}


@OnClose
public void onClose(Session session) {
onlineCount.decrementAndGet(); // 在线数减1
clients.remove(session.getId());
for (String key : WebSocketServer.clients.keySet()) {
if(key.contains(session.getId())){
clients.remove(key);
clients.remove(key.split("_")[0]);
break;
}
}
log.info(“有一连接关闭:{},当前在线人数为:{}”, session.getId(), onlineCount.get());
}


@OnMessage
public void onMessage(String message, Session session) {
log.info(“服务端收到客户端[{}]的消息[{}]”, session.getId(), message);
if(message.contains(session.getId())){
clients.put(message,session);//标识
}
/try {
this.sendMessage(“server say :hello-[”+session.getId()+ “] you say:”+message, session);
} catch (Exception e) {
log.error(“解析失败:{}”, e);
}
/
}

@OnError
public void onError(Session session, Throwable error) {
log.error(“发生错误”);
error.printStackTrace();
}


public static void sendMessage(String message, Session toSession) {
try {
log.info(“服务端给客户端[{}]发送消息[{}]”, toSession.getId(), message);
toSession.getBasicRemote().sendText(message);
} catch (Exception e) {
log.error(“服务端发送消息给客户端失败:{}”, e);
}
}
}


H5测试:

WebSocket Test Send Close

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4692574.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-07
下一篇 2022-11-07

发表评论

登录后才能评论

评论列表(0条)

保存