【发布时间】:2018-07-06 23:53:24
【问题描述】:
我试图编写一个程序来简单地将文件从客户端发送到服务器。该程序有一个 gui,您可以在其中输入文件路径以及您希望新文件名在服务器上的内容。该程序在第一次发送时工作正常,但在第二次发送时冻结,第二个文件没有写入服务器。任何帮助将不胜感激,我真的卡住了,非常感谢你们。
客户端代码
ServerSocket serverSocket;
public void sendFile(String filePath, String fileFieldName)throws IOException{
//Parameters filePath is a full direct path of file to be sent
//Example of filePath "C:\Users\Someone\Desktop\Capture3333333.PNG"
//FileFieldName is the desired name and extension of file being sent
// i removed my server ip and just put in a string for demonstration
Socket socket = new Socket("IP GOES HERE", 5557);
System.out.println("Is sending?");
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
File files = new File(filePath);
long length = files.length();
dos.writeLong(length);
dos.writeUTF("\\"+ fileFieldName);
FileInputStream fis = new FileInputStream(filePath);
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte = 0;
while((theByte = bis.read()) != -1) bos.write(theByte);
bis.close();
bos.flush();
dos.close();
}
服务器代码
ServerSocket serverSocket;
public void fileListenThread () throws IOException {
while(true){//This is so the socket keeps listening
serverSocket = new ServerSocket(5557);
Socket socket = serverSocket.accept();
if(socket.isConnected()){
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
File files ;
long fileLength = dis.readLong();//This reads file length from client
String fileName = dis.readUTF();//This reads filename from client
files = new File( System.getProperty("user.home") + "\\Desktop\\Top-Brand\\Images\\" + fileName );//File received from client is written to this path
FileOutputStream fos = new FileOutputStream(files);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for(int j = 0; j < fileLength; j++)
bos.write(bis.read());
bos.flush();
bos.close();
dis.close();
}
}
}
【问题讨论】:
-
调试客户端和服务器时会发生什么?卡在哪里了?
-
您好,我是新手,还没有弄清楚如何使用 netbeans 调试器。我将在 youtube 上观看操作方法。但是我确实又运行了几次程序并发现了一个错误,我能够连续复制 3 次。错误在服务器中:线程“主”java.net.BindException 中的异常:地址已在使用中:JVM_Bind 在 topbrandserver.TopBrandServer.fileListenThread(TopBrandServer.java:201)
标签: java file-transfer