android - 无法从 android okhttp3 连接到 Node websocket

标签 android node.js websocket socket.io okhttp

我在expressJs之上创建了一个 Node 服务器,并使用socket.io创建了一个websocket服务器。我用来创建服务器的代码是

io.sockets.on('connection', function (socket) {
    connections.push(socket);
    console.log('Connected: ' + connections.length + 'sockets connected');
    io.sockets.emit('connected', JSON.stringify({status: "online"}));

    socket.on('disconnect', function (data) {
        connections.splice(connections.indexOf(socket), 1);
        console.log('Disconnected: ' +  connections.length + ' sockets connected');
        io.sockets.emit('disconnected', {status: "offline"});
    });

    socket.on('request', function (data) {
        console.log('new request in server: ' + data.toString());
        io.sockets.emit('newRequest', JSON.stringify({request: data}));
    })
});

我可以从任何浏览器(包括移动浏览器和模拟器浏览器)连接到服务器,但我无法使用 okhttp3 websocket 连接。

我正在关注https://gist.github.com/AliYusuf95/557af8be5f360c95fdf029795291eddb创建客户端的要点。但我无法连接到 websocket。我收到以下错误 D/OkHttp: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on Connection{192.***.0.***:3000, proxy=DIRECT@ hostAddress=/192.***.0.***:3000:3000 cipherSuite=none protocol=http/1.1}

出了什么问题?

最佳答案

尝试以下操作...看看是否有效。

 private void connectWebSocket() {
  URI uri;
  try {
    uri = new URI("ws://websockethost:8080");
  } catch (URISyntaxException e) {
    e.printStackTrace();
    return;
  }

  mWebSocketClient = new WebSocketClient(uri) {
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
      Log.i("Websocket", "Opened");
      mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
    }

    @Override
    public void onMessage(String s) {
      final String message = s;
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          TextView textView = (TextView)findViewById(R.id.messages);
          textView.setText(textView.getText() + "\n" + message);
        }
      });
    }

    @Override
    public void onClose(int i, String s, boolean b) {
      Log.i("Websocket", "Closed " + s);
    }

    @Override
    public void onError(Exception e) {
      Log.i("Websocket", "Error " + e.getMessage());
    }
  };
  mWebSocketClient.connect();
}

Source

关于android - 无法从 android okhttp3 连接到 Node websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47876504/

相关文章:

Java:解压缩文件,而不创建目标文件夹

javascript - NodeJs-事件循环只处理 I/O 请求吗?

javascript - Socket.io 发送时间不一致

javascript - RXJS Stream - 如何等待我的流结束并返回数据,然后执行我的操作

java - ORMLite QueryBuilder.orderByRaw(String, SelectArg) 忽略 QueryBuilder.queryRaw() 上的 SelectArg

android - 保存Android项目以在PC上运行(eclipse)

android - 如何在应用程序中一直使用谷歌语音识别系统?

node.js - 避免使用 cy.wait() 等待页面由于中止的获取请求而加载 cypress

java - 泰鲁斯 wss ://websocket not passing through squid proxy

node.js - (索引):126 Uncaught DOMException: Failed to execute 'close' on 'WebSocket' : The code must be either 1000, 或 3000 到 4999 之间。0 两者都不是