未通过套接字从Python接收到Android的消息

未通过套接字从Python接收到Android的消息,android,python,sockets,client-server,Android,Python,Sockets,Client Server,我的android应用程序需要与python服务器通信,但在收到响应时,答案并不存在。这是我的密码: 这是我的客户: public class MainActivity extends Activity { private Socket socket; private static final int SERVERPORT = 5589; private static final String SERVER_IP = "192.168.1.131"; TextView risp; @Ove

我的android应用程序需要与python服务器通信,但在收到响应时,答案并不存在。这是我的密码:

这是我的客户:

public class MainActivity extends Activity {

private Socket socket;

private static final int SERVERPORT = 5589;
private static final String SERVER_IP = "192.168.1.131";
TextView risp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    risp = (TextView) findViewById(R.id.textView1);

    new Thread(new ClientThread()).start();
}

public void onClick(View view) {
    try {
        EditText et = (EditText) findViewById(R.id.editText1);
        String str = et.getText().toString();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())), true);
        out.println(str);
        out.flush();

        // Read from sock
        BufferedReader input = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = input.readLine()) != null) {
            response.append(line);
        }
        risp.setText(risp.getText().toString() + " " + response.toString());
        out.close();
        input.close();
        socket.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

    }

}
这是服务器:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('192.168.1.131', 5589)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)

while True:
        # Wait for a connection
        print >>sys.stderr, 'waiting for a connection'
        connection, client_address = sock.accept()
        try:
                print >>sys.stderr, 'connection from', client_address

                # Receive the data
                while True:
                        data = connection.recv(1024)
                        if data.lower() != 'q':
                                print "<-- client: ", data
                        else:
                                print "Quit from Client"
                                connection.close()
                                break
                        data = raw_input("--> server: ")
                        if data.lower() != 'q':
                                connection.sendall(data)
                        else:
                                print "Quit from Server"
                                connection.close()
                                break

        finally:
                # Clean up the connection
                print "Connection close"
                connection.close()
导入套接字
导入系统
#创建TCP/IP套接字
sock=socket.socket(socket.AF\u INET,socket.sock\u流)
#将套接字绑定到端口
服务器地址=('192.168.1.131',5589)
打印>>sys.stderr,'在%s端口%s%服务器地址上启动
sock.bind(服务器地址)
#侦听传入的连接
短袜,听(1)
尽管如此:
#等待连接
打印>>sys.stderr,“正在等待连接”
连接,客户端地址=sock.accept()
尝试:
打印>>sys.stderr,“连接自”,客户端地址
#接收数据
尽管如此:
数据=connection.recv(1024)
if data.lower()!='q':
打印“服务器:”)
if data.lower()!='q':
connection.sendall(数据)
其他:
打印“从服务器退出”
连接。关闭()
打破
最后:
#清理连接
打印“连接关闭”
连接。关闭()
服务器收到客户机消息,但客户机没有收到服务器消息。为什么?

提前谢谢大家

编辑:我是这样解决的:

public class MainActivity extends Activity {

    private Socket socket;

    private static final int SERVERPORT = 5589;
    private static final String SERVER_IP = "192.168.1.131";
    TextView risp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        risp = (TextView) findViewById(R.id.textView1);
        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 {
                EditText et = (EditText) findViewById(R.id.editText1);
                String str = et.getText().toString();
                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();
            }

        }

    }
}
公共类MainActivity扩展活动{
专用插座;
专用静态最终int服务器端口=5589;
私有静态最终字符串服务器\u IP=“192.168.1.131”;
文本视图risp;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
risp=(TextView)findViewById(R.id.textView1);
新线程(新ClientThread()).start();
}
公共void onClick(视图){
新建ConnectionTask().execute();
}
类ConnectionTask扩展了异步任务{
受保护的字符串doInBackground(字符串…参数){
字符串response=null;
试一试{
EditText et=(EditText)findViewById(R.id.editText1);
字符串str=et.getText().toString();
PrintWriter out=新的PrintWriter(新的BufferedWriter(
新的OutputStreamWriter(socket.getOutputStream()),true);
out.println(str);
out.flush();
InputStream输入=socket.getInputStream();
整数锁秒=10*1000;
long lockThreadCheckpoint=System.currentTimeMillis();
int availableBytes=input.available();

while(availableBytes)您的客户端正在尝试读取行。但是您的服务器正在发送行吗?我添加了日志。但是,服务器发送其响应,是客户端无法接收/读取。我使用client.py尝试了服务器,结果行得通,那么问题应该是或客户端,或服务器发送答案的方式(可能与java过程不同)。或者问题可能是getInputStream()没有阻塞..请重新阅读我所说的内容并对此作出反应。您的服务器是否正在发送线路?如果不发送,您的客户端将挂起。据我所知,正如您所说,程序在input.readLine()中崩溃.但是我的服务器发送响应,所以我不明白问题是什么。我也尝试从服务器自动发送标准响应,但没有任何更改。我没有说程序在readLine中崩溃。但是为什么你不告诉服务器是否发送行?我已经问了两次。现在是第三次了!