0

我写了一些客户端-服务器程序,它共享数据,但在服务器端我EOFException在接收数据后得到。我试图自己修复它,但很难找到自己的错误。

错误是由这一行引起的:Message command =(Message) serInputStream.readObject();

这是服务器的一些输出:

 java.io.EOFException

at Java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2577)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at transfer.Serwerus.run(Serwerus.java:42)

服务器代码:

import java.io.*;
import java.net.*;

public class Serwerus implements Runnable
{
public InputStream is;
public FileOutputStream fos;
public BufferedOutputStream bos;
public ObjectOutputStream serOutputStream;
public ObjectInputStream serInputStream;
ServerSocket socket;
private String clientMessage, clientFileName;
private int clientFileSize;

public Serwerus()
{
    try
    {
        socket = new ServerSocket(6060);
        System.out.println("Server started....");
    }
    catch(IOException e)
    {
        System.err.println("Error: " + e);
        e.printStackTrace();
    }
}

@Override
public void run()
{
    try 
        {
            Socket sock = socket.accept();
            System.out.println("Client accepted");
            serOutputStream = new ObjectOutputStream(sock.getOutputStream());
            serInputStream = new ObjectInputStream(sock.getInputStream());
          while (true) 
          {
              Message command =(Message) serInputStream.readObject();
              System.out.println("after readObject");
              if (command.getCommand().startsWith("FileU")) 
              {
                  System.out.println("Name = " + command.getfileName() + ", size= " + command.getfileSize());
                  serOutputStream.writeObject(new Message("Bring", "", 0));
                  //ReciveData(socket, command.getfileName(), command.getfileSize());
              }
              else if(command.getCommand().startsWith("Wait"))
              {
                  System.out.println("hohoho");
                  ReciveData(sock, command.getfileName(), command.getfileSize());
              }
              else if(command.getCommand().startsWith("Quit"))
              {
                  System.exit(1);
              }
              else
              {
                  System.out.println("Unknow");
              }
          }
        }
        catch(ClassNotFoundException | IOException ex)
        {
            ex.printStackTrace();
        } 
        finally 
        {
            try 
            {
                serInputStream.close();
                serOutputStream.close();
                socket.close();
            } 
            catch (IOException e) 
            {
                System.err.println("Fallen on closing socket.\n Error: " + e);
            }
        }
}

public void SendData(Socket sock, String filePath) throws Exception
{
    File myFile = new File (filePath);
    System.out.println("File name = " + myFile.getName() + " File len = " + (int)myFile.length());
    byte [] mybytearray  = new byte [(int)myFile.length()];
    FileInputStream fis = new FileInputStream(myFile);
    BufferedInputStream bis = new BufferedInputStream(fis);
    bis.read(mybytearray,0,mybytearray.length);
    OutputStream os = sock.getOutputStream();
    System.out.println("Sending...");
    os.write(mybytearray,0,mybytearray.length);
    os.flush();
    sock.close();
    System.out.println("Sending finished");
}

public void ReciveData(Socket sock, String filePath, int fileSize)
{
    System.out.println("Recive in progress, filesize = " + fileSize);
    int bytesRead = 0, current = 0;
    byte[] array = new byte[fileSize];

    try 
    {

        is = sock.getInputStream();
        FileOutputStream fos = new FileOutputStream(filePath);
        bos = new BufferedOutputStream(fos);
        do
        {
            System.out.println(bytesRead);
            bytesRead = is.read(array);
            current += bytesRead;
        }
        while(bytesRead > -1);

        bos.write(array, 0 , current);
        bos.flush();
        bos.close();
        fos.close();
       // sock.close();
        System.out.println("Reciveing finished");
    } 
    catch (IOException ex) 
    {
        ex.printStackTrace();
    }
}

 public static void main (String [] args ) throws IOException 
 {
     new Thread(new Serwerus()).start(); 
 }
}

客户端代码:

import java.io.*;
import java.net.*;

public class Clientus implements Runnable
{
    InputStream is;
    FileOutputStream fos;
    BufferedOutputStream bos;
    ObjectOutputStream cliOutputStream;
    ObjectInputStream cliInputStream;
    Socket socket;
    File actFile;
    private String serverMessage, serverFileName;
    private int serverFileSize;

    public Clientus()
    {
        try 
        {
            socket = new Socket("localhost", 6060);
            cliOutputStream = new ObjectOutputStream(socket.getOutputStream());
            cliInputStream = new ObjectInputStream(socket.getInputStream());
            File file = new File(<filepath>);
            actFile = file;
        } 
        catch (Exception e) 
        {
            System.err.println("Error: " + e);
            e.printStackTrace();
        }
    }

    @Override
    public void run()
    {
        try 
            {   
                cliOutputStream.writeObject(new Message("FileU", actFile.getPath(), (int) actFile.length()));
                cliOutputStream.flush();
              //while (true) 
              //{
                  Message command =(Message) cliInputStream.readObject();
                  if (command.getCommand().startsWith("File")) 
                  {
                      String name = command.getfileName();
                      int size = command.getfileSize();
                      System.out.println("Name = " + command.getfileName() + ", size= " + command.getfileSize());
                      if(size != 0 && !"".equals(name))
                      {
                          //ReciveData(socket, 0);
                      }
                  }
                  else if(command.getCommand().startsWith("Bring"))
                  {
                      cliOutputStream.writeObject(new Message("Wait", "D:\\KP2\\Serwer\\dupa.txt",(int) actFile.length()));
                      cliOutputStream.flush();
                      try 
                      {
                          SendData(socket, actFile.getPath());
                          //this.socket.close();
                      } 
                      catch (Exception ex) 
                      {
                         System.err.println("Error with: SendData()");
                      }
                  }
                  else if(command.getCommand().startsWith("Quit"))
                  {
                      System.exit(1);
                  }
                  else
                  {
                      System.out.println("Command unknown");
                  }
              //}
            }
            catch(ClassNotFoundException | IOException ex)
            {
                ex.printStackTrace();
            } 
            finally 
            {
                try 
                {
                    socket.close();
                    cliOutputStream.close();
                    cliInputStream.close();
                } 
                catch (IOException e) 
                {
                    System.err.println("Fallen on closing socket.\n Error: " + e);
                }
            }
    }

    public void SendData(Socket sock, String filePath) throws Exception
    {
        byte [] mybytearray  = new byte [(int) new File(filePath).length()];
        FileInputStream fis = new FileInputStream(filePath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(mybytearray,0,mybytearray.length);
        OutputStream os = sock.getOutputStream();
        System.out.println("Sending...");
        os.write(mybytearray,0,mybytearray.length);
        fis.close();
        bis.close();
        os.close();
        System.out.println("Sending finished");
    }

    public void ReciveData(Socket sock, String fileName, int fileSize)
    {
        int bytesRead, current = 0;
        byte[] array = new byte[fileSize+1];
        try 
        {
            is = sock.getInputStream();
            fos = new FileOutputStream(<file_path>);

            bos = new BufferedOutputStream(fos);
            bytesRead = is.read(array,0,array.length);

            current = bytesRead;
            do
            {
                bytesRead = is.read(array, current, (array.length - current));
                if(bytesRead >= 0)
                    current += bytesRead;
            }
            while(bytesRead > -1);

            bos.write(array, 0 , current);
            bos.flush();

            long end = System.currentTimeMillis();

            //System.out.println("Send time: " + (end - start));
            bos.close();
            sock.close();
            System.out.println("Reciveing finished");
        } 
        catch (IOException ex) 
        {
            ex.printStackTrace();
        }
    }

    public static void main (String [] args ) throws IOException 
    {
        new Thread(new Clientus()).start();
    }
}

任何人都可以帮忙吗?

4

2 回答 2

2

您的客户端在发送数据后可能会断开连接,并且由于您的服务器正在等待更多数据,因此EOFException会发生这种情况。

要解决此问题,您可以添加try-catch块以在客户端断开连接时捕获此异常。

于 2013-04-04T16:08:51.203 回答
0

您正在使用ObjectOutputStream套接字和套接字自己的OutputStream来发送数据,并且您正在不同步。当您直接通过套接字发送原始数据时,您不会先发送长度,因此接收方不知道有多少字节属于此传输。事实上,它只是在 EOS 之前读取所有内容,所以下次你调用ObjectInputStream.readObject()它时自然会得到 EOFException。要解决这个问题:

  1. ObjectInputStreamandObjectOutputStream用于一切
  2. 在发送文件之前,发送它的长度,通过writeLong().
  3. 在接收端,当接收到文件时,首先获取它的长度,readLong(),然后从 中读取那么多字节ObjectInputStream并将它们复制到文件中。
于 2013-04-05T00:18:23.997 回答