2021年5月18日:
今天完善了最基本的websocket代码,现在已经可以实现团员发送申请,然后社长得到请求:
package com.atguigu.crud.utils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/websocket/{userno}")
@Component
public class websocket {
private static ConcurrentHashMap<String, websocket> webSocketSet = new ConcurrentHashMap<String, websocket>();
private Session WebSocketsession;
private String userno = "";
@OnOpen
public void onOpen(@PathParam(value = "userno") String param, Session WebSocketsession, EndpointConfig config)
throws IOException {
userno = param;
this.WebSocketsession = WebSocketsession;
websocket webSocketServer = webSocketSet.get(param);
if (webSocketServer != null) { // 同样业务的连接已经在线,则把原来的挤下线。
webSocketServer.WebSocketsession.getBasicRemote().sendText(param + "重复连接被挤下线了");
webSocketServer.WebSocketsession.close();
}
webSocketSet.put(param, this);
}
@OnClose
public void onClose() {
if (!userno.equals("")) {
webSocketSet.remove(userno);
}
}
@OnMessage
public void onMessage(String message) {
if (message.split("[|]")[1].contains(",")) {
sendAll(message.split("[|]")[1].split(","));
} else {
sendToUser(message);
}
}
public void sendToUser(String message) {
String sendUserno = message.split("[|]")[1];
String sendMessage = message.split("[|]")[0];
try {
if (webSocketSet.get(sendUserno) != null) {
webSocketSet.get(sendUserno).sendMessage(sendUserno);
}
} catch (IOException e) {
}
}
private void sendAll(String a[]) {
for (String key : a) {
try {
if (webSocketSet.get(key) != null) {
webSocketSet.get(key).sendMessage(key);
}
} catch (IOException e) {
}
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.WebSocketsession.getBasicRemote().sendText(message);
}
}
这段后端的代码的意思在于当用户发起入团申请之后,界面就会发起一条信息传到websocket的服务器,当用户登录时就会连接到服务器然后就会发送一条信息给社长,但是现在有一个问题那就是如果社长没在线那就发不了,这个问题是我在做的过程中发现的,所以现在我要一种方法来解决如果别人断线的问题。