這是我的第一個問題。我尋找類似問題的解決方案,但在每種情況下都與我的情況相比有一些差異。 我正試圖建立一個Python服務器和使用套接字的Android應用程序之間的簡單連接。 Android應用程序啓動與服務器的對話:它向服務器發送消息,服務器接收並顯示它,然後服務器嚮應用程序發送回覆。該應用程序在TextView中的屏幕上顯示回覆。 這是我在客戶端代碼:Python服務器和Android應用程序之間的連接
public class MyClient extends Activity implements OnClickListener{
EditText enterMessage;
Button sendbutton;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.myclient);
enterMessage = (EditText)findViewById(R.id.enterMessage);
sendbutton = (Button)findViewById(R.id.sendbutton);
sendbutton.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
Thread t = new Thread(){
@Override
public void run() {
try {
Socket s = new Socket("192.168.183.1", 7000);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(enterMessage.getText().toString());
//read input stream
DataInputStream dis2 = new DataInputStream(s.getInputStream());
InputStreamReader disR2 = new InputStreamReader(dis2);
BufferedReader br = new BufferedReader(disR2);//create a BufferReader object for input
//print the input to the application screen
final TextView receivedMsg = (TextView) findViewById(R.id.textView2);
receivedMsg.setText(br.toString());
dis2.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
Toast.makeText(this, "The message has been sent", Toast.LENGTH_SHORT).show();
} }
而在服務器端,這是我的代碼:
from socket import *
HOST = "192.168.183.1" #local host
PORT = 7000 #open port 7000 for connection
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1) #how many connections can it receive at one time
conn, addr = s.accept() #accept the connection
print "Connected by: " , addr #print the address of the person connected
while True:
data = conn.recv(1024) #how many bytes of data will the server receive
print "Received: ", repr(data)
reply = raw_input("Reply: ") #server's reply to the client
conn.sendall(reply)
conn.close()
當我嘗試從應用程序到服務器時,它完美的作品發送郵件。但是,只要服務器收到消息並顯示消息,應用程序立即停止並顯示錯誤消息:意外停止。請再試一次。 附加信息:我正在使用adt-bundle for Android開發和IDLE來運行服務器代碼。無論在Windows8上。