Last active
April 30, 2016 08:32
-
-
Save omaraflak/8af66560824a7c7a504a54079aeb97f3 to your computer and use it in GitHub Desktop.
Socket class for Android that can be used with a NodeJS server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is how we use it: