

@ServerEndpoint(value = "/ws/asset")
@Component
public class WebSocketServer {
@PostConstruct
public void init() {
System.out.println("websocket 加载");
}
private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
@OnOpen
public void onOpen(Session session) {
SessionSet.add(session);
int cnt = OnlineCount.incrementAndGet();
log.info("有连接加入,当前连接数为:{}", cnt);
SendMessage(session, "连接成功");
}
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
int cnt = OnlineCount.decrementAndGet();
log.info("有连接关闭,当前连接数为:{}", cnt);
}
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:{}",message);
SendMessage(session, "收到消息,消息内容:"+message);
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误:{},Session ID:{}",error.getMessage(),session.getId());
error.printStackTrace();
}
public static void SendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));
} catch (IOException e) {
log.error("发送消息出错:{}", e.getMessage());
e.printStackTrace();
}
}
public static void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
if(session.isOpen()){
SendMessage(session, message);
}
}
}
public static void SendMessage(String message,String sessionId) throws IOException {
Session session = null;
for (Session s : SessionSet) {
if(s.getId().equals(sessionId)){
session = s;
break;
}
}
if(session!=null){
SendMessage(session, message);
}
else{
log.warn("没有找到你指定ID的会话:{}",sessionId);
}
}
}
ServerEndpointExporter对象创建
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter () {
return new ServerEndpointExporter();
}
}
测试Controller
@RestController
@RequestMapping("/api/ws")
public class WebSocketController {
@RequestMapping(value="/sendAll", method= RequestMethod.GET)
public String sendAllMessage(@RequestParam(required=true) String message){
try {
WebSocketServer.BroadCastInfo(message);
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
@RequestMapping(value="/sendOne", method=RequestMethod.GET)
public String sendOneMessage(@RequestParam(required=true) String message,@RequestParam(required=true) String id){
try {
WebSocketServer.SendMessage(message,id);
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>websocket测试</title>
<style type="text/css">
h3,h4{
text-align:center;
}
</style>
</head>
<body>
<h3>WebSocket测试,在<span style="color:red">控制台</span>查看测试信息输出!</h3>
<h4>
[url=/api/ws/sendOne?message=单发消息内容&id=none]单发消息链接[/url]
[url=/api/ws/sendAll?message=群发消息内容]群发消息链接[/url]
</h4>
<script type="text/javascript">
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("遗憾:您的浏览器不支持WebSocket");
} else {
console.log("恭喜:您的浏览器支持WebSocket");
socket = new WebSocket("ws://localhost:8080/ws/asset");
socket.onopen = function() {
console.log("Socket 已打开");
socket.send("消息发送测试(From Client)");
 {
console.log(msg.data);
};
socket.
socket.onclose = function() {
console.log("Socket已关闭");
};
socket.onerror = function() {
alert("Socket发生了错误");
}
window.unload=function() {
socket.close();
};
}
</script>
</body>
</html>

