The example in this article describes how the Python server communicates with the Android client socket. Share to everyone for your reference. The implementation method is as follows:
First, the server side is done with Python, and the following is the Python code:
The code is as follows:
#server. py
Import socket
def GETIPADDRS (hostname): #只是为了显示IP, just test it.
result = Socket.getaddrinfo (hostname, None, 0, socket. SOCK_STREAM)
return [x[4][0] for x in result]
Host = ' #为空代表为本地host
hostname = Socket.gethostname ()
HostIP = Getipaddrs (hostname)
Print (' Host IP ', hostip) #应该显示为: 127.0.1.1
Port = 9999 # arbitrary non-privileged Port
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
S.bind ((host, Port))
S.listen (4)
While True:
conn, addr = S.accept ()
Print (' Connected by ', addr)
data = CONN.RECV (1024)
If not data:break
Conn.sendall (data) #把接收到数据原封不动的发送回去
Print (' Received ', repr (data))
Conn.close ()
Here's the Android code:
The code is as follows:
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.util.Log;
public class TcpClient extends Activity {
/** called when the activity is first created. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Runtcpclient ();
Finish ();
}
private static final int tcp_server_port = 9999;//should is same to the SERVER PORT
private void Runtcpclient () {
try {
Socket s = new socket ("**.**.intel.com", tcp_server_port);//Note that host changes to your server's hostname or IP address
BufferedReader in = new BufferedReader (New InputStreamReader (S.getinputstream ()));
BufferedWriter out = new BufferedWriter (New OutputStreamWriter (S.getoutputstream ()));
Send Output MSG
String outmsg = "TCP connecting to" + Tcp_server_port + system.getproperty ("Line.separator");
Out.write (outmsg);//Send data
Out.flush ();
LOG.I ("TcpClient", "Sent:" + outmsg);
Accept Server Response
String inmsg = in.readline () + system.getproperty ("Line.separator");//Get data returned by the server
LOG.I ("TcpClient", "Received:" + inmsg);
Close connection
S.close ();
} catch (Unknownhostexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
}
Replace Runtcpclient () at OnCreate with this method if you want to run TCP client as a service
private void Runtcpclientasservice () {
Intent lintent = new Intent (This.getapplicationcontext (), tcpclientservice.class);
This.startservice (lintent);
}
}
The thing to note in the Android code is that the address of the server is to be written, and that the server can be accessed by your network segment.
Hopefully this article will help you with Python programming.