从Android Websocket客户端发送消息

时间:2017-09-27 17:50:46

标签: java android http websocket okhttp

我想从Android okhttp3 websocket客户端发送消息,而不仅仅是回应来自服务器的消息。这是我的websocket类:

 // Websocket
 public final class EchoWebSocketListener extends WebSocketListener {
     private static final int NORMAL_CLOSURE_STATUS = 1000;
     @Override
     public void onOpen(WebSocket webSocket, Response response) {
         webSocket.send(message);
     }
     @Override
     public void onMessage(WebSocket webSocket, String text) {
         printer("text);
     }
     @Override
     public void onClosing(WebSocket webSocket, int code, String reason) {
         webSocket.close(NORMAL_CLOSURE_STATUS, null);
     }
     @Override
     public void onFailure(WebSocket webSocket, Throwable t, Response response) {

     }
     public void send(WebSocket webSocket) {
       webSocket.send(finalMessage);
     }
 }

以下是我从onCreate方法中调用它的方法:

client= new OkHttpClient();
Request request = new Request.Builder().url(Url).build();
EchoWebSocketListener listener = new EchoWebSocketListener();
webso = myClient.newWebSocket(request, listener);
client.dispatcher().executorService().shutdown();

我尝试为该类创建一个对象并调用一个名为'send'的函数:

EchoWebSocketListener object = new EchoWebSocketListener ()
object.send(webso)

但那不起作用?

1 个答案:

答案 0 :(得分:0)

以这种方式推荐RxWebSocket