我有一个客户端和服务器,客户端服务器文件传输聊天的Java GUI
1)客户端应该发送选择文件,并将它们发送到服务器
2)客户端应该发送一个命令消息,使服务器知道传入的是一个文件不是消息(这就是为什么我有“SF”它代表发送文件)
3)服务器接收文件,并将它们在系统中
而且在一些地方保存,我不想我发送/接收文件后关闭套接字(因为这是在客户端点击断开连接按钮时完成的)
下面是我的代码,但由于某种原因,如果有人可以帮我修复它,它不起作用。
客户
public void sendFiles(String file) {
this.out.print("SF");
this.out.flush();
File myfile = new File(file);
// Get the size of the file
long length = myfile.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
FileInputStream fis;
try {
fis = new FileInputStream(myfile);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(sock.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
System.out.println("count "+bytes.length);
// this.out.flush();
out.flush();
// out.close();
fis.close();
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
服务器
public void recvFile() {
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
try {
is = sock.getInputStream();
bufferSize = sock.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
fos = new FileOutputStream("/Users/day/Documents/Parallels/server.txt");
bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
System.out.println("bytes "+bytes.length);
System.out.println("count "+count);
bos.flush();
bos.close();
// is.close();
// sock.close();
} catch (IOException e) {
System.out.println("ERROR" +e);
}
另外在服务器端;这是我如何跳转到方法recvFile();我的问题
if (message.contains("SF")) {
recvFile();
}
更多的解释: 它不,我不知道,如果该文件是实际发送正确感工作?或文件接收正确,因为我得到0字节在收到的文件。此外,这是我不想关闭连接的事情,因为这是一个聊天,所以我如何让服务器知道这是文件的结尾? 有人可以帮助我使代码工作,因为我不知道什么是错的?谢谢
定义“不起作用”。你知道它为什么不起作用吗? – immibis
此外,服务器如何知道它何时到达文件结尾(以便下一个命令再次是聊天消息)? – immibis
@immibis感谢您的回复。它不起作用,我不知道该文件是否实际发送正确?或文件接收正确,因为我得到0字节在收到的文件。此外,这是我不想关闭连接的事情,因为这是一个聊天,所以我如何让服务器知道这是文件的结尾? – Deyaa