我用Grizzly在java中设置websocket服务器。我的问题是我无法将广播公司设置为 websocket 以通过覆盖 WebSocketApplication
来使用优化的 websocket。我按照文档描述的方式进行操作。但我得到了这个错误。
方法setBroadcaster(Broadcaster)来自类型SimpleWebSocket 不可见。
这是我的代码
public class BroadcastApplication extends WebSocketApplication {
private final Broadcaster broadcaster;
public BroadcastApplication(Broadcaster broadcaster) {
this.broadcaster = broadcaster;
}
@Override public WebSocket createSocket(ProtocolHandler handler,
HttpRequestPacket requestPacket, WebSocketListener... listeners) {
final DefaultWebSocket ws = (DefaultWebSocket) super.createSocket(handler, requestPacket, listeners);
ws.setBroadcaster(broadcaster); // Got error here
return ws;
}
@Override public void onMessage(WebSocket socket, String data) {
socket.broadcast(getWebSockets(), data);
}
}
我的grizzly-websockets
版本是2.3.22
。欢迎任何建议。
这样的事情应该可以工作:
public class BroadcastApplication extends WebSocketApplication {
private final Broadcaster broadcaster;
public BroadcastApplication(Broadcaster broadcaster) {
this.broadcaster = broadcaster;
}
@Override
public WebSocket createSocket(ProtocolHandler handler,
HttpRequestPacket requestPacket, WebSocketListener... listeners) {
return new BroadcastWebSocket(broadcaster, handler, requestPacket, listeners);
}
@Override
public void onMessage(WebSocket socket, String data) {
socket.broadcast(getWebSockets(), data);
}
private static class BroadcastWebSocket extends DefaultWebSocket {
public BroadcastWebSocket(Broadcaster broadcaster,
ProtocolHandler protocolHandler,
HttpRequestPacket request,
WebSocketListener... listeners) {
super(protocolHandler, request, listeners);
this.broadcaster = broadcaster;
}
}
}