我对python有问题 recv()
功能。我有客户端java和服务器python,我想向客户端发送命令。没有 connection.recv()
数据已发送,但 connection.recv()
未发送数据和java readLine()
正在等待输入。
这是我的python服务器:-
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("192.168.1.8", 2307))
sock.listen()
con, adr = sock.accept()
con.sendall(b"download test.txt")
data = con.recv(4096)
这是我的java客户端:-
import java.io.*;
import java.net.Socket;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws IOException {
Socket Client = new Socket("192.168.1.8", 2307);
DataOutputStream Output = new DataOutputStream(Client.getOutputStream());
DataInputStream Input = new DataInputStream(Client.getInputStream());
FileInputStream getFileStream = null;
int bufLength = 2048;
byte[] buffer = new byte[2048];
String savePath = "C:\\Users\\Aragami\\Desktop\\Python\\test.txt";
byte[] data;
String str = "";
String ack;
try {
str = Input.readLine();
}catch (Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
if(str.split(" ")[0].trim().equals("download")) {
String fileName = str.split(" ")[1].trim();
getFileStream = new FileInputStream("C:\\Users\\Aragami\\IdeaProjects\\droidClient\\src\\" + fileName);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int readLength;
while ((readLength = getFileStream.read(buffer, 0, bufLength)) != -1) {
out.write(buffer, 0, readLength);
}
data = out.toByteArray();
String imageString = Base64.getEncoder().encodeToString(data);
FileWriter fileWriter = new FileWriter(savePath);
int firstIndex = 0;
int lastIndex = 4096;
int lengthOfFile = imageString.length();
while(lengthOfFile > 0)
{
if(lengthOfFile >= 4096)
{
Output.writeUTF(imageString.substring(firstIndex,lastIndex));
firstIndex += 4096;
lastIndex += 4096;
lengthOfFile -= 4096;
}
else
{
lastIndex = (lastIndex - 4096) + lengthOfFile;
lengthOfFile = 0;
Output.writeUTF(imageString.substring(firstIndex,lastIndex));
}
ack = Input.readLine();
}
Output.writeUTF("DONE");
fileWriter.write(imageString);
// close streams
fileWriter.close();
out.close();
getFileStream.close();
}
}
当我使用 readUTF()
返回异常:-
at java.io.DataInputStream.readFully(DataInputStream.java:195)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
update:- the 问题是使用python的eo命令,您必须发送以'\n'结尾的数据,因此java代码很清楚,但是python代码将是:-
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("192.168.1.8", 2307))
sock.listen()
con, adr = sock.accept()
con.sendall(b"download test.txt" + b'\n') # <= Here its
data = con.recv(4096)
暂无答案!
目前还没有任何答案,快来回答吧!