package org.example.websocket.server;
|
|
import com.google.gson.Gson;
|
import com.google.gson.reflect.TypeToken;
|
import lombok.NonNull;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.stereotype.Component;
|
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.RequestBody;
|
|
import javax.websocket.*;
|
import javax.websocket.server.ServerEndpoint;
|
import java.io.IOException;
|
import java.lang.reflect.Type;
|
import java.util.Map;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
/**
|
* @ClassDescription: websocket服务端
|
* @JdkVersion: 1.8
|
* @Created: 2023/8/31 14:59
|
*/
|
@Slf4j
|
@Component
|
@ServerEndpoint("/websocket-server")
|
public class WsServer {
|
|
private Session session;
|
private static AtomicInteger onlineCount = new AtomicInteger(0);
|
private static CopyOnWriteArrayList<WsServer> wsServers = new CopyOnWriteArrayList<>();
|
|
@OnOpen
|
public void onOpen(Session session) {
|
this.session = session;
|
int count = onlineCount.incrementAndGet();
|
wsServers.add(this);
|
log.info("与客户端连接成功,当前连接的客户端数量为:{}", count);
|
}
|
|
@OnError
|
public void onError(Session session, @NonNull Throwable throwable) {
|
log.error("连接发生报错");
|
throwable.printStackTrace();
|
}
|
|
@OnClose
|
public void onClose() {
|
int count = onlineCount.decrementAndGet();
|
wsServers.remove(this);
|
log.info("服务端断开连接,当前连接的客户端数量为:{}", count);
|
}
|
|
@OnMessage
|
public void sendMessage(String message) throws IOException {
|
Map<String, Object> map = jsonToMap(message);
|
if(map.get("pid").equals("00000001")){
|
System.out.println(message);
|
}
|
try {
|
if (session.isOpen()) {
|
this.session.getBasicRemote().sendText(message);
|
}
|
} catch (IOException e) {
|
throw new IOException("消息发送失败", e);
|
}
|
}
|
|
public void sendMessageToAll(String message) throws IOException {
|
for (WsServer wsServer : wsServers) {
|
wsServer.sendMessage(message);
|
}
|
}
|
|
|
@PostMapping("/send2AllC")
|
public void sendMessageToAll1(@RequestBody String message) throws IOException {
|
CopyOnWriteArrayList<WsServer> ws = wsServers;
|
for (WsServer wsServer : ws){
|
wsServer.sendMessage(message);
|
}
|
}
|
|
public static Map<String, Object> jsonToMap(String json) {
|
Gson gson = new Gson();
|
Type type = new TypeToken<Map<String, Object>>(){}.getType();
|
return gson.fromJson(json, type);
|
}
|
|
}
|