2

I built a server using node.js and socket.io for a chat application and I want to connect to the server from my android client application that uses native java.net.Socket. Can I do it?

Md. Yamin Mollah
  • 1,609
  • 13
  • 26

3 Answers3

1

Here I found a solution that works fine. This code section is for server side socket.

var net = require('net');
var sockets = [];

var svr = net.createServer(function(sock) {
    console.log('Connected: ' + sock.remoteAddress + ':' + sock.remotePort);
    sockets.push(sock);

    sock.write('Welcome to the server!\n');

    sock.on('data', function(data) {
        for (var i=0; i<sockets.length ; i++) {
            if (sockets[i] != sock) {
                if (sockets[i]) {
                    sockets[i].write(data);
                }
            }
        }
    });

    sock.on('end', function() {
        console.log('Disconnected: ' + sock.remoteAddress + ':' + sock.remotePort);
        var idx = sockets.indexOf(sock);
        if (idx != -1) {
            delete sockets[idx];
        }
    });
});

var svraddr = '192.168.0.8';
var svrport = 1234;

svr.listen(svrport, svraddr);
console.log('Server Created at ' + svraddr + ':' + svrport + '\n');

Android client side code is given below: connect to the given ip and port for server through android client side.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Client {
private Socket socket;
private OutputStream socketOutput;
private BufferedReader socketInput;

private String ip;
private int port;
private ClientCallback listener=null;

public Client(String ip, int port){
    this.ip=ip;
    this.port=port;
}

public void connect(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            socket = new Socket();
            InetSocketAddress socketAddress = new InetSocketAddress(ip, port);
            try {
                socket.connect(socketAddress);
                socketOutput = socket.getOutputStream();
                socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                new ReceiveThread().start();

                if(listener!=null)
                    listener.onConnect(socket);
            } catch (IOException e) {
                if(listener!=null)
                    listener.onConnectError(socket, e.getMessage());
            }
        }
    }).start();
}

public void disconnect(){
    try {
        socket.close();
    } catch (IOException e) {
        if(listener!=null)
            listener.onDisconnect(socket, e.getMessage());
    }
}

public void send(String message){
    try {
        socketOutput.write(message.getBytes());
    } catch (IOException e) {
        if(listener!=null)
            listener.onDisconnect(socket, e.getMessage());
    }
}

private class ReceiveThread extends Thread implements Runnable{
    public void run(){
        String message;
        try {
            while((message = socketInput.readLine()) != null) {   // each line must end with a \n to be received
                if(listener!=null)
                    listener.onMessage(message);
            }
        } catch (IOException e) {
            if(listener!=null)
                listener.onDisconnect(socket, e.getMessage());
        }
    }
}

public void setClientCallback(ClientCallback listener){
    this.listener=listener;
}

public void removeClientCallback(){
    this.listener=null;
}

public interface ClientCallback {
    void onMessage(String message);
    void onConnect(Socket socket);
    void onDisconnect(Socket socket, String message);
    void onConnectError(Socket socket, String message);
}
}

MainActivity is:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Client socket = new Client("192.168.0.8", 1234);
    socket.setClientCallback(new Client.ClientCallback () {
        @Override
        public void onMessage(String message) {
        }

        @Override
        public void onConnect(Socket socket) {
                socket.send("Hello World!\n");
                socket.disconnect();
        }

        @Override
        public void onDisconnect(Socket socket, String message) {
        }

        @Override
        public void onConnectError(Socket socket, String message) {
        }
    });

    socket.connect();
}
}
Md. Yamin Mollah
  • 1,609
  • 13
  • 26
0

The answer to your question is No. A java.net.socket cannot be connected with a nodejs socket.io because the protocol specifications are different for both.

Note: Socket.IO is not a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the ack id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server (like ws://echo.websocket.org) either. Please see the protocol specification here.

Quoted From nodejs socket.io github page.So when web socket cannot be connected to socket.io so the java.net.socket can also be not connected. If you want to have communication with the java client you can use the Socket.io library designed for java.

-1

In Nodejs, You can use from this example

And in Sockect.io blog

In Java, as a server, you can use PrintWriter to write your data on Socket in a very simple situation. like below open socket on port 9090 and send current date to the client:

/**
 * Runs the server.
 */
public static void main(String[] args) throws IOException {
    ServerSocket listener = new ServerSocket(9090);
    try {
        while (true) {
            Socket socket = listener.accept();
            try {
                PrintWriter out =
                    new PrintWriter(socket.getOutputStream(), true);
                out.println(new Date().toString());
            } finally {
                socket.close();
            }
        }
    }
    finally {
        listener.close();
    }
}

Code from here

SadeghAlavizadeh
  • 609
  • 3
  • 17
  • 33
  • I do not want to use Socket.io in android, want to use java.net.socket ... can you explain it? – Md. Yamin Mollah Feb 28 '18 at 06:33
  • I already made a server using node.js and socket.io but in the client side I am using android and I want to connect the app to the node.js server using java.net.socket in android clint side not server side. Thank you for your try, but it does not help me out – Md. Yamin Mollah Feb 28 '18 at 07:02