pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
增加bean
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
数据交互
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.websocket.WsSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {
private Session session;
private String userId;
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
private static XxxService xxxService;
@Autowired
public void setChatService(XxxService xxxService) {
WebSocketServer.xxxService = xxxService;
}
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId") String userId){
this.session = session;
this.userId = userId;
webSocketMap.put(userId, this);
}
@OnClose
public void onClose(){
webSocketMap.remove(userId);
}
@OnError
public void onerror(Session session, Throwable throwable)
{
log.info("socket communicate exception.");
}
@OnMessage
public void onMessage(Session session, String message){
JSONObject messageJson;
try {
messageJson = JSON.parseObject(message);
}catch(Exception e) {
return;
}
String name = messageJson.getString("Id");
Long Id = messageJson.getLong("Id");
String userId = messageJson.getString("userId");
Object obj = XxxService.query(Id, name);
JSONObject result = new JSONObject();
result.put("msgId", "MsgInfo");
result.put("msgContent", JSON.toJSON(obj));
String resultString = result.toJSONString();
appointSending(userId, resultString);
}
public void appointSending(String userId, String message)
{
try {
webSocketMap.get(userId).session.getBasicRemote().sendText(message);
}catch (Exception e){
log.error(String.format("fail to sendMessage, userId is %s", userId));
}
}
}