okhttp中的多个连接websocket

Multiple connections websocket in okhttp

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

我想将聊天模块添加到 android 应用程序。我正在为 websocket 客户端使用 okhttp。从设备连接时它正在工作。但是当连接第二个设备时它不工作。只有第一个设备 websocket.on("message") 事件发射器响应。 另一个设备不听消息。只有 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} 

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

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