您好我在Python 2.7中创建简单的通信服务器,我的第一个目标是使用套接字将“list”发送到Android App。
import socket
import sys
HOST = '192.168.0.108' # this is your localhost
PORT = 8888
list=str(["firstitem",'nextitem'])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# socket.socket: must use to create a socket.
# socket.AF_INET: Address Format, Internet = IP Addresses.
# socket.SOCK_STREAM: two-way, connection-based byte streams.
print 'socket created'
# Bind socket to Host and Port
try:
s.bind((HOST, PORT))
except socket.error as err:
print 'Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1]
sys.exit()
print 'Socket Bind Success!'
# listen(): This method sets up and start TCP listener.
s.listen(10)
print 'Socket is now listening'
while 1:
conn, addr = s.accept()
print 'Connect with ' + addr[0] + ':' + str(addr[1])
#receiver
buf = conn.recv(64)
#sender
send=conn.send(list)
print buf
print 'Connect close with ' + addr[0] + ':' + str(addr[1])
s.close()
我想从python serwer读取列表然后创建BufferedReader(new InputStreamReader)以从python接收数据但是不能正常工作。
package com.javacodegeeks.android.androidsocketclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 8888;
private static final String SERVER_IP = "192.168.0.108";
private BufferedReader input;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) throws IOException {
try {
this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
} catch (IOException e)
{
e.printStackTrace();
}
String read = input.readLine();
Log.d("INFO", "onClick: "+read.toString());
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
您有什么想法我无法阅读此列表吗?