-
Notifications
You must be signed in to change notification settings - Fork 2
WebSocketServer
Xiao Yu edited this page Jun 2, 2019
·
1 revision
public class ChatServerTest {
public static void main(String[] args) {
WebSocketServer server = new WebSocketServer(2222, new WebSocketRequestHandler() {
@Override
public void onOpen(WebSocketChannel webSocketChannel) {
LOG.info("建立连接: {},", webSocketChannel, getWebSocketChannels().size());
getWebSocketChannels().forEach(d -> {
if (!webSocketChannel.equals(d)) {
d.send("> " + webSocketChannel.getQueryParam("name") + ",加入聊天");
}
});
}
@Override
public void onMessage(WebSocketChannel webSocketChannel, String message) {
LOG.info("收到消息, {}: {}", webSocketChannel.getQueryParam("name"), message);
getWebSocketChannels().forEach(d -> {
if (!webSocketChannel.equals(d)) {
d.send(webSocketChannel.getQueryParam("name") + ": " + message);
}
});
}
@Override
public void onClose(WebSocketChannel webSocketChannel, int code, String reason, boolean remote) {
LOG.info("关闭连接: {}, code: {}, reason: {}, remote: {}, open: {}", webSocketChannel, code, reason, remote, webSocketChannel.isOpen());
getWebSocketChannels().forEach(d -> {
if (!webSocketChannel.equals(d) && d.isOpen()) {
d.send("> " + webSocketChannel.getQueryParam("name") + ",退出聊天");
}
});
}
@Override
public void onError(WebSocketChannel webSocketChannel, Throwable throwable) {
LOG.error("发生异常: {}", webSocketChannel, throwable);
}
});
System.out.println("启动结果:" + server.isOpen());
}
}
可以使用在线模拟websocket请求工具进行测试。