Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有EOFEException的Java流_Java_Objectinputstream_Objectoutputstream_Eofexception - Fatal编程技术网

带有EOFEException的Java流

带有EOFEException的Java流,java,objectinputstream,objectoutputstream,eofexception,Java,Objectinputstream,Objectoutputstream,Eofexception,我编写了一些客户机-服务器程序,共享数据,但在服务器端,我收到数据后得到了EOFException。我试图自己修复它,但很难找到自己的错误 错误是由以下行引起的:Message命令=(Message)serInputStream.readObject() 以下是服务器的一些输出: java.io.EOFException at Java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2577

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

错误是由以下行引起的:
Message命令=(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();
    }
}
import java.io.*;
导入java.net。*;
公共类Clientus实现了Runnable
{
输入流为;
文件输出流;
缓冲输出流;
ObjectOutputStream cliOutputStream;
ObjectInputStream cliInputStream;
插座;
文件actFile;
私有字符串serverMessage,serverFileName;
私有int-serverFileSize;
公共客户()
{
尝试
{
套接字=新套接字(“localhost”,6060);
cliOutputStream=newObjectOutputStream(socket.getOutputStream());
cliInputStream=newobjectinputstream(socket.getInputStream());
File File=新文件();
actFile=文件;
} 
捕获(例外e)
{
System.err.println(“错误:+e”);
e、 printStackTrace();
}
}
@凌驾
公开募捐
{
尝试
{   
cliOutputStream.writeObject(新消息(“FileU”,actFile.getPath(),(int)actFile.length());
cliOutputStream.flush();
//while(true)
//{
Message命令=(Message)cliInputStream.readObject();
if(command.getCommand().startsWith(“文件”))
{
String name=command.getfileName();
int size=command.getfileSize();
System.out.println(“Name=“+command.getfileName()+”,size=“+command.getfileSize());
如果(大小!=0&&!“.equals(名称))
{
//接收数据(套接字,0);
}
}
else if(command.getCommand().startsWith(“带”))
{
cliOutputStream.writeObject(新消息(“Wait”,“D:\\KP2\\Serwer\\dupa.txt”,(int)actFile.length());
cliOutputStream.flush();
尝试
{
SendData(socket,actFile.getPath());
//this.socket.close();
} 
捕获(例外情况除外)
{
System.err.println(“错误:SendData()”;
}
}
else if(command.getCommand().startsWith(“退出”))
{
系统出口(1);
}
其他的
{
System.out.println(“命令未知”);
}
//}
}
捕获(ClassNotFoundException | IOException ex)
{
例如printStackTrace();
} 
最后
{
尝试
{
socket.close();
cliOutputStream.close();
cliInputStream.close();
} 
捕获(IOE异常)
{
System.err.println(“落在关闭的套接字上。\n错误:+e”);
}
}
}
public void SendData(套接字套接字、字符串文件路径)引发异常
{
byte[]mybytearray=新字节[(int)新文件(filePath).length()];
FileInputStream fis=新的FileInputStream(filePath);
BufferedInputStream bis=新的BufferedInputStream(fis);
读取(mybytearray,0,mybytearray.length);
OutputStream os=sock.getOutputStream();
System.out.println(“发送…”);
write(mybytearray,0,mybytearray.length);
fis.close();
二、关闭();
os.close();
System.out.println(“发送完成”);
}
public void ReciveData(套接字套接字、字符串文件名、int fileSize)
{
int字节读取,当前=0;
字节[]数组=新字节[文件大小+1];
尝试
{
is=sock.getInputStream();
fos=新文件输出流();
bos=新的缓冲输出流(fos);
bytesRead=is.read(数组,0,数组.length);
当前=字节读取;
做
{
bytesRead=is.read(array,current,(array.length-current));
如果(字节读取>=0)
电流+=字节读取;
}
while(bytesRead>-1);
写入(数组,0,当前);
bos.flush();
long end=System.currentTimeMillis();
//System.out.println(“发送时间:+(结束-开始));
bos.close();
sock.close();
System.out.println(“接收完成”);
} 
捕获(IOEX异常)
{
例如printStackTrace();
}
}
公共静态void main(字符串[]args)引发IOException
{
新线程(新Clientus()).start();
}
}

有人能帮忙吗?

您的客户端在发送数据后可能会断开连接,因为您的服务器正在等待更多数据,因此将发生
EOFEException


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

您正在使用
ObjectOutputStream
和套接字自己的
OutputStream
发送数据,并且正在失去同步。当您直接通过套接字发送原始数据时,您不会首先发送长度,因此接收器不知道有多少字节属于此传输。实际上,它只是读取所有内容直到EOS,所以下次调用
ObjectInputStream.readObject时