Its just a simple python client to interact with a python server, i am trying now to implement the following code on Android app but i am new to Android, any help?
import socket
import json
host='127.0.0.1'
port=9090
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host,port))
while True:
data = "Message to send"
sock.send(data)
response = json.loads(sock.recv(1024))
print response
sock.close()
quit()
I have this for now, since its running on a Fragment i had to create a new thread since connections should not be done on UI Thread.
class ClientThread implements Runnable {
@Override
public void run() {
final String msg = "message to send";
Log.d(msg, "sending this");
try {
String msg_received = null;
System.out.println("TRYING TO CONNECT");
InetAddress serverAddr = InetAddress.getByName(HOST);
Socket socket = new Socket(HOST, PORT);
System.out.println("CONNECTED");
System.out.println(socket.getLocalAddress());
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(msg);
output.flush();
// Get data sent through socket
DataInputStream DIS = new DataInputStream(socket.getInputStream());
// read data that got sent
msg_received = DIS.readUTF();
System.out.println("Message from server" + msg_received);
socket.close();
} catch (Exception e) {
System.out.println("Did not receive string");
}
}
}
Nothing is being printed after
Socket socket = new Socket(HOST, PORT);
Where did i got this wrong?