通过socket将字符串从android客户端发送到python服务器

时间:2016-02-11 18:35:58

标签: java android python sockets raspberry-pi

我用Google搜索并查看了几乎所有的stackoverflow解决方案和Android文档,但我无法做到。这是我的服务器端代码: -

import socket
import time

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#host = socket.gethostname()
host = "192.168.1.100"
port = 6000
serversocket.bind((host,port))

serversocket.listen(5)
def sample1():
    print "the data has arrived"
    clientsocket.send("success")

def sample2():
    print "the data"
    clientsocket.send("success again")

while True:
    clientsocket, addr = serversocket.accept()
    print("Got a connection from %s" % str(addr))

    while 1:
        data3 = clientsocket.recv(1024)
        data4 = data3.strip()
        if data4 == "hello":
            sample1()
        elif data4 == "hi":
            sample2()
        else:
            print "random data"
        if data4 == "stop":
            break

这是我在android上的客户端代码: -

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main22Activity extends Activity {

private Socket socket;

private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.1.100";
TextView risp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main22);
    risp = (TextView) findViewById(R.id.display);
    new Thread(new ClientThread()).start();

}

public void onClick(View view) {
    new ConnectionTask().execute();
}

class ConnectionTask extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... params) {
        String responce = null;
        try {
            String str = "hello";
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            out.println(str);
            out.flush();

            InputStream input = socket.getInputStream();
            int lockSeconds = 10*1000;

            long lockThreadCheckpoint = System.currentTimeMillis();
            int availableBytes = input.available();
            while(availableBytes <=0 && (System.currentTimeMillis() < lockThreadCheckpoint + lockSeconds)){
                try{Thread.sleep(10);}catch(InterruptedException ie){ie.printStackTrace();}
                availableBytes = input.available();
            }

            byte[] buffer = new byte[availableBytes];
            input.read(buffer, 0, availableBytes);
            responce = new String(buffer);

            out.close();
            input.close();
            socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responce;
    }
    protected void onPostExecute(String responce) {
        risp.setText(responce);
    }
}

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();
        }

    }

}
}
单击按钮时会触发

onClick事件。所有权限防火墙设置也检查它们没问题。在打开应用程序时,它连接到python服务器(它显示它收到了连接)。单击时,它首先发送字符串hello,使其跳转到sample1函数,android也在textView中接收消息成功。但在此之后它并没有停止并且python服务器继续永久打印随机数据,再次点击按钮没有任何反应。我希望我的客户端在按下后只发送一次hello,获取数据,更新UI并等到再次按下按钮。最初,我使用这个覆盆子pi获取温度数据所以每次温度变化,python服务器将发送数据,我想在我的Android应用程序上显示它,而无需按任何按钮。我该怎么做我原本打算做的事情?修改后的代码将不胜感激。谢谢。

0 个答案:

没有答案