gpt4 book ai didi

java - 无法从套接字读取

转载 作者:太空宇宙 更新时间:2023-11-04 10:32:32 25 4
gpt4 key购买 nike

我已经设置了一个 pi 零,在我的本地网络上运行一个简单的 python 服务器脚本来响应某些命令。我正在尝试从 android java 应用程序发送这些命令。但是当我尝试读取我发送的命令的回复时,它似乎跳过了该行。因为“D/正在发送数据:数据已发送”是最后打印到日志中的内容。

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

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])

最佳答案

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

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

关于java - 无法从套接字读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49842248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com