pom需要引入包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketServer:
package com.wiiteer.aaron.config;
import com.alibaba.fastjson.JSONObject;
import com.wiiteer.aaron.vo.MessageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@ServerEndpoint(value = "/websocket/aaron/{uuid}")
@Component
public class WebSocketServer {
//WebSocket连接池
private static ConcurrentHashMap<String, WebSocketServer> web_socket_pool = new ConcurrentHashMap<>();//线程安全的map
//与某个客户端的连接会话,通过session来给客户端发送数据
private Session session;
/**
* 连接成功后调用的方法
*
* @param uuid
* @param session
*/
@OnOpen
public void onOpen(@PathParam("uuid") String uuid, Session session) {
this.session = session;
//存储上线客户端
web_socket_pool.put(uuid, this);
log.info("web成功连接:" + uuid);
}
/**
* 连接关闭后调用的方法
*
* @param uuid
*/
@OnClose
public void onClose(@PathParam("uuid") String uuid) {
//移出上线客户端
web_socket_pool.remove(uuid);
log.info("web关闭连接:" + uuid);
}
/**
* 连接出错时调用的方法
*
* @param session
* @param error
*/
@OnError
public void onError(@PathParam("uuid") String uuid, Session session, Throwable error)
{
error.printStackTrace();
log.info("连接出错时:" + uuid);
}
/**
* 收到客户端消息后调用的方法
*
* @param uuid
* @param message
*/
@OnMessage
public void onMessage(@PathParam("uuid") String uuid, String message) {
log.debug("来自" + uuid + "客户端的消息:" + message);
}
/**
* 发送自定义消息给客户端
* 实际干活的方法
*
* @param message
*/
public void sendMessage(MessageVo message) {
try {
this.session.getBasicRemote().sendText(JSONObject.toJSONString(message));
} catch (Exception e) {
log.error("发送自定义消息给客户端异常:" + e.getLocalizedMessage());
}
}
}
WebSocketConfig:
package com.wiiteer.aaron.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}