我试图通过TCP套接字将文件从Python服务器发送到Java客户机。以下是我目前所掌握的情况:
Java客户端(请注意,所有文件传输代码都在getFile()方法中):
public class Client1
{
private Socket socket = null;
private FileOutputStream fos = null;
private DataInputStream din = null;
private PrintStream pout = null;
private Scanner scan = null;
public Client1(InetAddress address, int port) throws IOException
{
System.out.println("Initializing Client");
socket = new Socket(address, port);
scan = new Scanner(System.in);
din = new DataInputStream(socket.getInputStream());
pout = new PrintStream(socket.getOutputStream());
}
public void send(String msg) throws IOException
{
pout.print(msg);
pout.flush();
}
public void closeConnections() throws IOException
{
// Clean up when a connection is ended
socket.close();
din.close();
pout.close();
scan.close();
}
// Request a specific file from the server
public void getFile(String filename)
{
System.out.println("Requested File: "+filename);
try {
File file = new File(filename);
// Create new file if it does not exist
// Then request the file from server
if(!file.exists()){
file.createNewFile();
System.out.println("Created New File: "+filename);
}
fos = new FileOutputStream(file);
send(filename);
// Get content in bytes and write to a file
int counter;
byte[] buffer = new byte[8192];
while((counter = din.read(buffer, 0, buffer.length)) != -1)
{
fos.write(buffer, 0, counter);
} }
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以及Python服务器:
^{pr2}$我能够成功地在服务器和客户机之间创建一个消息传递程序,在这里它们互相传递字符串。但是,我无法通过网络传输文件。在
Python服务器似乎正确地发送了字节,因此Java端似乎是问题所在。尤其是while循环:while((counter = din.read(buffer, 0, buffer.length)) != -1)
已经给出了一个-1
的输出,因此文件的写入实际上从未发生过。在
提前感谢您的帮助!在
作为其他人的参考,这是我如何使它最终工作。在
服务器:
客户:
^{pr2}$相关问题 更多 >
编程相关推荐