Search code examples
androidnode.jswebsocketautobahn

Node Server with Android and Browser Client


EDIT: I want to implement a quiz-application on Android and Browser via Web Interface. I'm looking for a way to communicate between the server and the clients. I tried socket.io but couldn't get it working with android.

I'm using a node.js server hosted on nodester (nodester.com). I tried some libs but couldn't get it working.

I'm now working with einaros/ws from https://github.com/einaros/ws

The server code is:

var clients = [],
numClients = 0;


var WebSocketServer = require('ws').Server,
  wss = new WebSocketServer({port: 20083});

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

  ws.on('message', function(message) {
    console.log(wss.clients);
    console.log('received: %s', message);
    incomingMessage(message, ws)
  });

  /*
  ws.on('eigenesEvent', function(message) {
    console.log('eigenes Event ausgelöst: ' + message);
  });
  */
});

function incomingMessage(msg, ws) {
  //console.log(wss.clients);
  var obj = JSON.parse(msg);

    if(obj.type == "connect") {

      for(var i=0;i<clients.length;i++) {
        if(clients[i] == obj.id) {
          ws.send(JSON.stringify({
            to: obj.id,
            message: "name vergeben"
          }));
          return;
        }
      }
      clients[numClients] = obj.id;
      numClients++;
      for(var i=0;i<clients.length;i++) {
        console.log("Client" + i + ": " + clients[i]);
      }
      ws.send(JSON.stringify({
          to: "all",
          message: obj.id + " connected"
      }));
    }

  if(obj.type == "disconnect") {

    for(var i=0;i<clients.length;i++) {
      if(clients[i] == obj.id) {
        clients.splice(i, 1);
        numClients--;
        for(var i=0;i<clients.length;i++) {
          console.log("Client" + i + ": " + clients[i]);
        }
      }
    }

    ws.send(JSON.stringify({
      to: "all",
      message: obj.id + " disconnected"
    }));
    return;
  }

  if(obj.type == "answer") {
    if("id" in obj) {
      if(obj.answer == "a") {
        ws.send(JSON.stringify({
          to: obj.id,
          message: "a is correct"
        }));
      } else {
        ws.send(JSON.stringify({
          to: obj.id,
          message: "answer is incorrect"
        }));
      }
    }
  }

  if(obj.type == "something") {
    if("id" in obj) {
      ws.send(JSON.stringify({
        to: obj.id,
        message: "received: " + obj.message
      }));
    }
  }
}



From a HTML-Site i can connect to the server via:

connect = function() {
    var host = "ws://einaros.nodester.com";

        try{
            socket = new WebSocket(host);
            console.log('WebSocket - status ' + socket.readyState);

            socket.onopen = function(msg) {
                console.log("Welcome - status " + this.readyState);
                socket.send(JSON.stringify({
                    id: model.getClientName(),
                    type: "connect"
                }));
                model.setConnectionStatus(true);
            };

            socket.onmessage = function(msg) {
                console.log("onmessage - msg: " + msg.data);
                checkMessage(msg.data);
            };

            socket.onclose = function(msg) {
                console.log("Disconnected - status " + this.readyState);
                model.setConnectionStatus(false);
            };

        }
        catch(ex){
            console.log(ex);
        }
},



On the Android-Client side i'm using AutobahnAndroid from: http://autobahn.ws/android
The client code for android is:

package ps.mediengestaltung;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;


public class MainActivity extends Activity {



public final WebSocketConnection mConnection = new WebSocketConnection();

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);


    final String wsuri = "ws://einaros.nodester.com";

    try {
        mConnection.connect(wsuri, new WebSocketHandler() {

            @Override
            public void onOpen() {
                Log.d("TAG", "Status: Connected to " + wsuri);
                mConnection.sendTextMessage("Hello Server!");
            }

            @Override
            public void onTextMessage(String payload) {
                Log.d("TAG", "Got echo: " + payload);
            }

            @Override
            public void onClose(int code, String reason) {
                Log.d("TAG", "Connection lost.");
            }
        });
    } catch (WebSocketException e) {
        Log.d("TAG", e.toString());
    }

}

}


In LogCat i get:
08-01 08:48:13.017: D/TAG(704): Status: Connected to ws://einaros.nodester.com
08-01 08:48:13.167: D/TAG(704): Connection lost.


What am i doing wrong? Any hints?


Solution

  • The reason could be: Weberknecht only implements the (outdated) Hixie-76 version of WebSocket.

    You might try AutobahnAndroid, which implements the final RFC6455 version of WebSocket.

    Another things: the WebSocket server you are using is no longer maintained (as far as I know). It also only implements Hixie-76 - which is no longer supported by Chrome/Firefox.

    Try one of these:

    Disclaimer: I am the author of Autobahn and work for Tavendo.