无法从套接字读取

时间:2018-04-15 13:04:58

标签: java android sockets

我在本地网络上设置了一个运行简单python服务器脚本的pi 0来响应某些命令。我试图从Android Java应用程序发送这些命令。但是当我尝试从我发送的命令中读取回复时,它似乎就是划线了。因为“D /发送数据:数据已发送”是打印到日志的最后一件事。

这是我用来发送命令然后从服务器打印回复的嵌套runnable类:

private class SendData implements Runnable
    {
        private byte[] dataToSend;
        private Socket socket;
        private OutputStream outputStream;

        private BufferedReader bufferedReader;

        public SendData(Socket socket, byte[] dataToSend)
        {
            this.socket = socket;
            this.dataToSend = dataToSend;
        }

        @Override
        public void run()
        {
            try
            {
                outputStream = socket.getOutputStream();
                outputStream.write(dataToSend);
                Log.d("Sending data", "Data has been send");
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                Log.d("Received", bufferedReader.readLine());

            }
            catch (IOException e)
            {
                Log.e("IOException Sending data", e.getMessage());
            }
        }
    }

但是当我尝试从bufferedreader读取时,应用程序就退出了。虽然服务器确实发送了回复。

线程从这个方法开始,其中“data”是一个字符串。

if (socket != null)
        {
            Thread sendThread = new Thread(new SendData(socket, data.getBytes()));
            Log.d("SocketClient send", "Starting send thread");
            sendThread.start();
            try
            {
                sendThread.join();
            }
            catch (InterruptedException e)
            {
                Log.d("SocketClient constructor", "Could not join");
            }
        }
        else
        {
            Log.d("SocketClient send", "Socket is null");
        }

在pi上运行的Python脚本:

import socket
import sys
from datetime import datetime

host = "192.168.4.1"
port = 12345

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

sock.bind((host, port))

sock.listen(1)

def data_client(conn, ipStr):
    while True:
        data = conn.recv(2048)
        reply = handle_command(data)
        print "Command: %s" % data
        if not data or data == "con_close":
            print "Connection %s closed" % ipStr
            break
        conn.send(reply)
        print "Send: %s" % reply
    conn.close()

def handle_command(cmd):
    if (cmd == "con_close"):
        return cmd
    elif (cmd == "get_time"):
        return str(datetime.now())
    else:
        return "err_invalid_command"

while True:
    print "listening:"
    conn, addr = sock.accept()
    print "Got connection from %s" % addr[0]
    data_client(conn, addr[0])

1 个答案:

答案 0 :(得分:0)

如果接收者试图读取一行,则发送者应该发送一行。

接收方尝试读取readLine()的行,但readLine()永远不会返回,因为它等待尚未发送的换行符。