本文實例講述了python服務器與android客戶端socket通信的方法。分享給大家供大家參考。具體實現方法如下:
首先,服務器端使用python完成,下面為python代碼:
復制代碼
代碼如下:
#server.py?
import socket?
def getipaddrs(hostname):#只是為了顯示IP,僅僅測試一下?
??? 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()
import socket?
def getipaddrs(hostname):#只是為了顯示IP,僅僅測試一下?
??? 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()
下面是Android代碼:
復制代碼
代碼如下:
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 be same to the server port?
??? private void runTcpClient() {?
??????? try {?
??????????? Socket s = new Socket("**.**.intel.com", TCP_SERVER_PORT);//注意host改成你服務器的hostname或IP地址?
??????????? 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);//發送數據?
??????????? out.flush();?
??????????? Log.i("TcpClient", "sent: " + outMsg);?
??????????? //accept server response?
??????????? String inMsg = in.readLine() + System.getProperty("line.separator");//得到服務器返回的數據?
??????????? 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);?
??? }?
}
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 be same to the server port?
??? private void runTcpClient() {?
??????? try {?
??????????? Socket s = new Socket("**.**.intel.com", TCP_SERVER_PORT);//注意host改成你服務器的hostname或IP地址?
??????????? 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);//發送數據?
??????????? out.flush();?
??????????? Log.i("TcpClient", "sent: " + outMsg);?
??????????? //accept server response?
??????????? String inMsg = in.readLine() + System.getProperty("line.separator");//得到服務器返回的數據?
??????????? 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);?
??? }?
}
安卓代碼中要注意的就是服務器的地址要寫對,而且要保證服務器是可以被你的網段訪問的。
希望本文所述對大家的Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
