Skip to content

Instantly share code, notes, and snippets.

@omaraflak
Last active April 30, 2016 08:32
Show Gist options
  • Save omaraflak/8af66560824a7c7a504a54079aeb97f3 to your computer and use it in GitHub Desktop.
Save omaraflak/8af66560824a7c7a504a54079aeb97f3 to your computer and use it in GitHub Desktop.
Socket class for Android that can be used with a NodeJS server.
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) {
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);
}
}
@omaraflak
Copy link
Author

omaraflak commented Apr 26, 2016

This is how we use it:

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!");
        socket.disconnect();
    }

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

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

socket.connect();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment