我已成功为tomcat websockets实现了一个简单的echo服务器示例。现在我需要从我的服务器向客户端发送连续消息。我如何实现这一目标?
显示服务器端代码
package org.playjava.websocket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import javax.servlet.http.HttpServletRequest;
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 SimpleEchoServlet extends WebSocketServlet {
@Override
protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr) {
return new SimpleEchoInbound();
}
private static final class SimpleEchoInbound extends MessageInbound {
public SimpleEchoInbound() {
super();
}
@Override
protected void onBinaryMessage(ByteBuffer message) throws IOException {
getWsOutbound().writeBinaryMessage(message);
}
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
getWsOutbound().writeTextMessage(message);
getWsOutbound().writeTextMessage(message);
getWsOutbound().writeTextMessage(message);
}
}
}
答案 0 :(得分:0)
在SimpleEchoInbound的构造函数中启动一个线程,并在该线程中调用getWsOutbound()。writeTextMessage()。
顺便说一句,您正在使用Tomcat专有的WebSocket API,该API已在Tomcat 7中弃用,并且已完全在Tomcat 8中删除。您应该切换到完全支持的JSR-356 Java WebSocket API Tomcat 7和Tomcat 8。