android 手机 与 python服务器_Python服务器与Android应用程序的连接

这是我的第一个问题。我一直在寻找类似问题的解决方案,但在每一个案例中,都有一些不同于我的案例。

我试图在Python服务器和使用sockets的Android应用程序之间建立一个简单的连接。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()

当我尝试从应用程序向服务器发送消息时,它工作得很好。但是,一旦服务器收到并显示消息,应用程序立即停止,并显示错误消息:has stopped unexpectly。请再试一次。

附加信息:我使用adt bundle进行Android开发,并使用IDLE运行服务器代码。都在8号窗口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值