okhttp

时间:2018-11-29 18:36:04

标签: java android websocket okhttp okhttp3

我是使用nodejs(ws库)开发的websocket服务器

我想将聊天模块添加到android应用程序。我正在为Websocket客户端使用okhttp。从设备连接时,它正在工作。但是,当连接第二台设备时,它不起作用。仅第一个设备websocket.on(“ message”)事件发射器响应。 另一个设备不监听onMessage。只有A设备在听A。B-> B

如何配置onMessage在所有设备上均可使用。

java客户端:

class SConnection {
    SConnection(String url) {
        mClient = new OkHttpClient.Builder()
                .readTimeout(3,  TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

        mServerUrl = url;
    }

    public enum ConnectionStatus {
        DISCONNECTED,
        CONNECTED
    }

    public interface ServerListener {
        void onNewMessage(String message);
        void onStatusChange(ConnectionStatus status);
    }

    private WebSocket mWebSocket;
    private OkHttpClient mClient;
    private String mServerUrl;
    private Handler mMessageHandler;
    private Handler mStatusHandler;
    private ServerListener mListener;


    public class SocketListener extends WebSocketListener {
        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            Message m = mStatusHandler.obtainMessage(0, ConnectionStatus.CONNECTED);
            mStatusHandler.sendMessage(m);
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            Message m = mMessageHandler.obtainMessage(0, text);
            mMessageHandler.sendMessage(m);
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            Message m = mStatusHandler.obtainMessage(0, ConnectionStatus.DISCONNECTED);
            mStatusHandler.sendMessage(m);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            disconnect();
        }
    }

    void connect(ServerListener listener) {
        Request request = new Request.Builder()
                .url(mServerUrl)
                .build();
        mWebSocket = mClient.newWebSocket(request, new SocketListener());
        mListener = listener;
        mMessageHandler = new Handler(msg -> {mListener.onNewMessage((String) msg.obj);  return true;});
        mStatusHandler = new Handler(msg -> { mListener.onStatusChange((ConnectionStatus) msg.obj);   return true;});
    }

    void disconnect() {
        mWebSocket.cancel();
        mListener = null;
        mMessageHandler.removeCallbacksAndMessages(null);
        mStatusHandler.removeCallbacksAndMessages(null);
    }

    void sendMessage(String message) {
        mWebSocket.send(message);
    }

nodejs中的Websocket服务器:

module.exports = (httpsServer) => {

    const WebSocketServer = require('ws').Server;
    const wss = new WebSocketServer({
        server: httpsServer
    });

    wss.on('connection', function connection(ws) {
        console.log('connected');

        ws.on('message', function incoming(message) {
            ...
            ws.send(JSON.stringify(response));
        });
    });
    wss.on('close', function close() {
        console.log('disconnected');
    });
};

也许添加了此解决问题,但是如何解决?

{'force new connection':true} 

1 个答案:

答案 0 :(得分:1)

首先了解该问题,阅读所有评论

wss.on('connection', function connection(ws) {

    // So here ws is the user got connected
    console.log('connected');    

    // This will be fired when connected user send message
    ws.on('message', function incoming(message) {
        ...
        // this will send message to the same user
        ws.send(JSON.stringify(response));
    });

});

解决方案:因此,您要做的就是获取所有客户并将其发送给所有期望的自己,这就是您可以做到的方式:

ws.on('message', function incoming(data) {
    // Broadcast to everyone else.
    wss.clients.forEach(function each(client) {
        if (client !== ws && client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
});

更多信息 DO READ