我不禁认为有一个非常简单的解决方案,但到目前为止还没有运气。我想我已经走到了互联网的边缘并回头看,阅读了整个 RFC6455 以了解幕后发生的事情等。我使用 eclipse 进行开发,并在开发机器上运行了最新的 tomcat。
这是我的测试类,eclipse 甚至不会编译,因为它表明我需要删除受保护的 StreamInbound 方法上的 @Override。实际写法:
wsListenerTest 类型的方法 createWebSocketInbound(String) 必须覆盖或实现超类型方法;
它建议删除@Override。
我正在尝试在没有任何其他服务器或插件的情况下完成 Tomcat 本地的所有操作。
提前致谢
package com.blah.blah;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;
public class wsListenerTest extends WebSocketServlet {
private static final long serialVersionUID = 1L;
static int numConnections = 0;
private static final String GUEST_PREFIX = "Guest";
private final AtomicInteger connectionIds = new AtomicInteger(0);
private final Set<ChatMessageInbound> connections = new CopyOnWriteArraySet<ChatMessageInbound>();
@Override
protected StreamInbound createWebSocketInbound(String subProtocol) {
return new ChatMessageInbound(connectionIds.incrementAndGet());
}
private final class ChatMessageInbound extends MessageInbound {
private final String nickname;
private ChatMessageInbound(int id) {
this.nickname = GUEST_PREFIX + id;
}
@Override
protected void onOpen(WsOutbound outbound) {
connections.add(this);
String message = String.format("* %s %s",
nickname, "has joined.");
broadcast(message);
}
@Override
protected void onClose(int status) {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
}
@Override
protected void onBinaryMessage(ByteBuffer message) throws IOException {
throw new UnsupportedOperationException(
"Binary message not supported.");
}
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
// Never trust the client
// String filteredMessage = String.format("%s: %s",nickname, HTMLFilter.filter(message.toString()));
broadcast(message.toString());
}
private void broadcast(String message) {
for (ChatMessageInbound connection : connections) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
connection.getWsOutbound().writeTextMessage(buffer);
} catch (IOException ignore) {
// Ignore
}
}
}
}
}