websocket聊天体验
light-example-4j/websocket目录有client-to-server、peer-to-peer两个示例项目,解决了我的两个问题:在线聊天、日志查看。
在线聊天,后续可以支持:最近历史、表情+图片
.addPrefixPath("/ws/chat", websocket(new WebSocketConnectionCallback() {
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
channel.getReceiveSetter().set(new AbstractReceiveListener() {
@Override
protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
Set<WebSocketChannel> peerConnections = channel.getPeerConnections();
String msg = channel.getSourceAddress()+"/"+peerConnections.size()+": "+message.getData();
peerConnections.parallelStream().forEach(c -> WebSockets.sendText(msg, c, null));
log.info(msg);//可以看到当前有多少人
}
});
channel.resumeReceives();
}
}))
日志查看:使用Tailer、TailerListenerAdapter,把日志信息推送给浏览器。