通过套接字发送两个文件时出错

时间:2016-10-17 11:15:08

标签: java network-programming

我正在尝试通过套接字发送两个文件,但不幸的是我收到了错误:

  

java.io.EOFException的

我发布了服务器端和客户端代码。请帮我通过套接字发送这两个文件。

ServerSocket servsock = null; /* initilization */
Socket sock = null;
//Socket sock = null;
try {
System.out.println("waiting please connect the device");
servsock = new ServerSocket(5555); /* port number */
sock=servsock.accept();
System.out.println("waiting...");

BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
DataInputStream dis = new DataInputStream(bis);

/* read the length of the file */
long fileLength = dis.readLong();
fos = new FileOutputStream(FILE_TO_RECEIVED1);
bos = new BufferedOutputStream(fos);

for(int j = 0; j < fileLength; j++)
bos.write(bis.read());    
bos.close();
/* once the first file is read , I  have closed the BOS */

/* code to read the second file */
long fileLength1 = dis.readLong();
fos = new FileOutputStream(FILE_TO_RECEIVED2);/* path where  
         second file should be stored  */
bos = new BufferedOutputStream(fos);
/* read the second file  */ 
for(int j = 0; j < fileLength1; j++) 
bos.write(bis.read());

bos.close();
dis.close();

GUI端代码     //通过套接字发送两个文件的代码

BufferedOutputStream bos = new  
BufferedOutputStream(sock.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
System.out.println("Accepted connection : " + sock);

File myFile1 = new File (FILE_TO_SEND1);
long length = myFile1.length();
dos.writeLong(length); //sending length of the file

fis = new FileInputStream(myFile1);
bis = new BufferedInputStream(fis);
int theByte = 0;
while((theByte = bis.read()) != -1) bos.write(theByte); 
/*sending first file */
bis.close();
fis.close(); 
dos.close();                        

dos = new DataOutputStream(bos);

File myFile2 = new File (FILE_TO_SEND2);
long length1 = myFile2.length();
dos.writeLong(length);

fis = new FileInputStream(myFile1);
bis = new BufferedInputStream(fis);
int theByte1 = 0;
/*sending second  file */

while((theByte = bis.read()) != -1) bos.write(theByte);
bis.close();

1 个答案:

答案 0 :(得分:0)

在GUI端代码上发送两个文件但在发送第二个文件时

 fis = new FileInputStream(myFile1);

您已经将fileinputstream两次发送到myFIle1,第二次将其更改为myFile2