import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @ClassName WebSocketConfig
* @Description: websocket集成配置
* @Author
* @Date 2020/1/2 16:56
* @Version V1.0
**/
@Configuration
public class WebSocketConfig {
/**
* 服务器节点
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
/**
* @ClassName ServerConfigurator
* @Description: server 配置,进行行为修改,鉴权等曹邹
* @Author
* @Date 2020/1/4 11:11
* @Version V1.0
**/
@Slf4j
@Component
public class ServerConfigurator extends ServerEndpointConfig.Configurator {
/**
* token鉴权认证 临时写死123
* @param originHeaderValue
* @return
*/
@Override
public boolean checkOrigin(String originHeaderValue) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
String token = request.getParameter("token");
LogUtil.info(log,"---->>>>> token {0}",token);
if("123".equals(token)) {
return super.checkOrigin(originHeaderValue);
}else{
return false;
}
}
/**
* Modify the WebSocket handshake response
* 修改websocket 返回值
* @param sec
* @param request
* @param response
*/
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
super.modifyHandshake(sec, request, response);
}
}
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.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName WebSocketServer
* @Description: websocket 服务处理核心类 sid 请求唯一标识 不能重复
* @Author
* @Date 2020/1/2 17:00
* @Version V1.0
**/
@ServerEndpoint(value = "/websocket/{sid}", configurator = ServerConfigurator.class)
@Component
@Slf4j
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private AtomicInteger onlineCount = new AtomicInteger();
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid 请求唯一标识
private String sid = "";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
this.sid = sid;
LogUtil.info(log,"有新窗口开始监听:" + sid + ",当前在线人数为" + getOnlineCount());
LogUtil.info(log, "cid ---->>>{0}", sid);
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
LogUtil.info(log,"有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
LogUtil.info(log,"收到来自窗口" + sid + "的信息:" + message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
LogUtil.error(log,"websocket发生错误");
error.printStackTrace();
}
/**
* 当前客户端发送消息
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 异步推送消息
*
* @param message
*/
public static void sendWholeAsyncMessage(String message) {
for (WebSocketServer item : webSocketSet) {
try {
item.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
LogUtil.error(log,"websocket异步发送消息异常{0}",e);
continue;
}
}
}
/**
* 群发自定义消息
*/
public static void sendInfo(@PathParam("sid") String sid, String message) throws IOException {
LogUtil.error(log,"推送消息到窗口" + sid + ",推送内容:" + message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if (sid == null) {
item.sendMessage(message);
} else if (item.sid.equals(sid)) {
item.sendMessage(message);
}
} catch (IOException e) {
LogUtil.error(log,"websocket发送消息异常{0}",e);
continue;
}
}
}
private int getOnlineCount() {
return onlineCount.get();
}
private void addOnlineCount() {
onlineCount.incrementAndGet();
}
private void subOnlineCount() {
onlineCount.decrementAndGet();
}
}
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;
/**
* @ClassName WebSocketClientTest
* @Description: web socket test 类
* @Author
* @Date 2020/1/6 9:54
* @Version V1.0
**/
@Slf4j
public class WebSocketClientTest extends Thread {
private String uri;
private CountDownLatch countDownLatch;
public WebSocketClientTest(String uri, CountDownLatch countDownLatch) {
this.uri = uri;
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
getClient(uri);
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 获取客户端连接实例
*
* @param uri
* @return
*/
public WebSocketClient getClient(String uri) {
try {
//创建客户端连接对象
WebSocketClient client = new WebSocketClient(new URI(uri)) {
/**
* 建立连接调用
* @param serverHandshake
*/
@Override
public void onOpen(ServerHandshake serverHandshake) {
log.info(uri+"===建立连接===");
}
/**
* 收到服务端消息调用
* @param s
*/
@Override
public void onMessage(String s) {
log.info(uri+"====收到来自服务端的消息===" + s);
}
/**
* 断开连接调用
* @param i
* @param s
* @param b
*/
@Override
public void onClose(int i, String s, boolean b) {
log.info("关闭连接:::" + "i = " + i + ":::s = " + s + ":::b = " + b);
}
/**
* 连接报错调用
* @param e
*/
@Override
public void onError(Exception e) {
log.error("====出现错误====" + e.getMessage());
}
};
//请求与服务端建立连接
client.connect();
//判断连接状态,0为请求中 1为已建立 其它值都是建立失败
while (client.getReadyState().ordinal() == 0) {
try {
Thread.sleep(200);
} catch (Exception e) {
log.warn("延迟操作出现问题,但并不影响功能");
}
log.info("连接中.......");
}
//连接状态不再是0请求中,判断建立结果是不是1已建立
if (client.getReadyState().ordinal() == 1) {
return client;
}
if (!(client.getReadyState().ordinal() == 1 || client.getReadyState().ordinal() == 0)) {
log.info(uri+"连接失败.......");
}
} catch (URISyntaxException e) {
log.error(e.getMessage());
}
return null;
}
import java.util.concurrent.CountDownLatch;
/**
* @ClassName WebSocketTest
* @Description: websocket 并发测试类
* @Author
* @Date 2020/1/6 10:00
* @Version V1.0
**/
public class WebSocketTest {
public static void main(String[] args) {
String urlPre = "ws://localhost:9029/websocket/";
int threadNum = 1000;
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
String url = urlPre +"NO"+i+"?token=123";
new WebSocketClientTest(url, countDownLatch).start();
countDownLatch.countDown();
}
}
}
<!-- websocket begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.4.0</version>
</dependency>
<!-- websocket end -->
websocket 集群建议使用token 集中存储管理