eclipse Python Server 与 Android 应用程序之间的连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22910351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connection between Python Server and Android Application
提问by shallawati
This is my first question. I have looked for solutions of similar problems but in every case there were some differences comparing to my case. I am trying to establish a simple connection between a Python server and an Android application using sockets. The Android app starts a conversation with the server: it sends a message to the server, the server receives and displays it, then the server sends a reply to the app. The app displays the reply on the screen in a TextView. This is my code on the client side:
这是我的第一个问题。我一直在寻找类似问题的解决方案,但在每种情况下,与我的情况相比都有一些差异。我正在尝试使用套接字在 Python 服务器和 Android 应用程序之间建立简单的连接。Android 应用程序开始与服务器对话:它向服务器发送消息,服务器接收并显示该消息,然后服务器向应用程序发送回复。该应用程序在 TextView 的屏幕上显示回复。这是我在客户端的代码:
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();
} }
And on the server side this is my code:
在服务器端,这是我的代码:
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()
When I try to send a message from the app to the server it works perfectly. However, as soon as the server receives the message and displays it, the app immediately stops with the error message: has stopped unexpectedly. Please try again. Additional info: I am using adt-bundle for Android development and IDLE to run the server code. Both on Windows8.
当我尝试从应用程序向服务器发送消息时,它运行良好。但是,一旦服务器收到消息并显示它,应用程序就会立即停止并显示错误消息:已意外停止。请再试一次。附加信息:我使用 adt-bundle 进行 Android 开发,并使用 IDLE 来运行服务器代码。两者都在 Windows8 上。
采纳答案by Periklis Douvitsas
From what I understand you use a thread in order to call the server but in the same thread you try to post back results to the UI.
据我了解,您使用线程来调用服务器,但在同一个线程中,您尝试将结果回发到 UI。
final TextView receivedMsg = (TextView) findViewById(R.id.textView2); receivedMsg.setText(br.toString());
final TextView receivedMsg = (TextView) findViewById(R.id.textView2); receivedMsg.setText(br.toString());
If you use your own Java thread you have to handle the following requirements in your own code: Synchronization with the main thread if you post back results to the user interface. I dont see that you are doing this.You either have to use a Handler or maybe you should consider using the Asynctask of android. With the AsyncTAsk you can write in the UI after this method is triggered. onPostExecute(Result) Invoked on the UI thread after the background computation finishes.
如果您使用自己的 Java 线程,则必须在自己的代码中处理以下要求: 如果将结果回发到用户界面,则与主线程同步。我没有看到你在做这个。你要么必须使用一个处理程序,要么你应该考虑使用 android 的 Asynctask。使用 AsyncTAsk,您可以在触发此方法后在 UI 中进行编写。onPostExecute(Result) 在后台计算完成后在 UI 线程上调用。
So inside this method you can write in the UI. have a look at these links http://learningdot.diandian.com/post/2014-01-02/40060635109Asynctask vs Thread in android
所以在这个方法中,你可以在 UI 中编写。看看这些链接 http://learningdot.diandian.com/post/2014-01-02/40060635109 Asynctask vs Thread in android
回答by Richard Green
You are writing to a GUI object in a non gui thread. You need to use a handler in order to pass the message back to GUI thread.
您正在非 gui 线程中写入 GUI 对象。您需要使用处理程序将消息传递回 GUI 线程。
Look at here for a fairly simple example : Update UI through Handler
在这里查看一个相当简单的示例:通过处理程序更新 UI