2
我不禁想起有一個非常簡單的解決方案,但沒有運氣到目前爲止。 我想我已經走到了互聯網的邊緣,回頭看,閱讀整個RFC6455,瞭解幕後的情況等。 我使用eclipse進行開發,並在開發機器上運行最新的tomcat。試圖在tomcat 7上實現非常基本的聊天(最新版本7.0.34)
這是我的測試類,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
}
}
}
}
}