2014-03-25 164 views
1

我已成功爲tomcat websockets實現了一個簡單的echo服務器示例。現在我需要從我的服務器向客戶端發送連續的消息。我如何實現這一目標?Apache Tomcat websockets服務器端消息

目前服務器端代碼

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

開始在SimpleEchoInbound的構造器線程,並調用getWsOutbound()。writeTextMessage()在該線程。

順便說一下,您正在使用Tomcat專有的WebSocket API,該API在Tomcat 7中已棄用,並且已完全在Tomcat 8中刪除。您應該切換到Tomcat 7中完全支持的JSR-356 Java WebSocket API和Tomcat 8.