2021年5月17日:
今天写了一个简单的后端代码是关于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 static Map<String, List<String>> map = new HashMap<>();
private static List<String> list = new ArrayList<>();
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);
if (map.get(param) != null) {
webSocketSet.get(param).sendMessage(param);
}
}
@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);
} else {
if (map.get(sendUserno) == null) {
map.put(sendUserno, list);
map.get(sendUserno).add(sendMessage);
} else {
map.get(sendUserno).add(sendMessage);
}
}
} catch (IOException e) {
}
}
此段代码还没有完善,只是完成了个人的通信和回复,并且前端代码比较复杂,现在只弄了一些简单的代码:
function send() {
var message = "用户" + userno + "向你发送一条入团申请";
var ToSendUserno = msg.substring(13, msg.length);
message1 = message + "|" + ToSendUserno;
websocket.send(message1);
sendmessage(ToSendUserno, messagec, "申请", userno, imgpath);
}
这就是团员发给社长的那个简单的代码
这是websocket连接的代码:
if (userno) {
websocket.onopen = function() {
if (msg.length > 0) {
if (msg.indexOf("成功") >= 0) {
alert("申请成功!请等待社长回应");
send();
window.location.href = "${pageContext.request.contextPath}/club/sousuo";
} else {
alert(msg);
}
}
}
websocket.onmessage = function(event) {
messageupdate(event.data);
}
window.onbeforeunload = function() {
websocket.close();
}
}