2

I've created a node server on top of expressJs and used socket.io to create a websocket server. Code i've used to create the server is

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}));
    })
});

I can connect with the server from any browser including mobile and emulator browser, But i failed to connect using okhttp3 websocket.

I am following https://gist.github.com/AliYusuf95/557af8be5f360c95fdf029795291eddb this gist to create the client. but i failed to connect with the websocket. I'm getting the following error 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}

What's going wrong?

ARiF
  • 1,079
  • 10
  • 23

1 Answers1

0

Try the following...see if that works.

 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

fida1989
  • 3,234
  • 1
  • 27
  • 30