【问题标题】:Stuck in write operation when reading from Socket从 Socket 读取时卡在写操作中
【发布时间】:2018-12-19 04:33:47
【问题描述】:

我正在通过 Socket 将文件及其名称发送到 ServerSocket。 它“部分”工作——服务器获取文件并将其保存到磁盘但是 它不会在 ClientSession 类的 copy() 方法中退出循环。

public class Client{
   DataOutputStream dos =null;
   DataInputStream dis=null; 
   File f =new File("c:/users/supernatural.mp4");
  public static void main(String[]ar) throws Exception{
    try {
          System.out.println("File upload started");
          Socket socc = new Socket("localhost",8117);
          dos = new DataOutputStream(socc.getOutputStream());
          //send file name
          dos.writeUTF(f.getName());
          //send the file
          write(f,dos);
          //Files.copy(f.toPath(),dos);
          //this prints
          System.out.println("Data has been sent...waiting for server to respond ");
          dis = new DataInputStream(socc.getInputStream());
          //this never reads; stuck here
          String RESPONSE = dis.readUTF();
          //this never prints prints
          System.out.println("Server sent: "+RESPONSE);
        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
          //close the exceptions
       clean();
        }
  }

  private static void write(File f,DataOutputStream d) throws Exception{
                int count;
                DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream(f)));
                byte array[] = new byte[1024*4];
                while((count =din.read(array)) >0){
                    d.write(array,0,count);
                }
                d.flush();
        //this prints
                System.out.println(" done sending...");
                din.close();    
    }
    }

    //Server
    public class MySocket implements Runnable{

        int worker_thread=2;
        volatile boolean shouldRun =false;
        ServerSocket server;
        String port = "8117";
        //ExecutorService services;
        static ExecutorService services;

    public MySocket() {
            this.server = new ServerSocket(Integer.valueOf(port));
            services = Executors.newFixedThreadPool(this.worker_thread);
        }
       //A METHOD TO RUN SERVER THREAD
        @Override
       public void run(){
           while(this.shouldRun){
               Socket client =null;
               try{
               client = server.accept();
               }catch(Exception ex){
                   ex.printStackTrace();
               }
               //hand it over to be processed
               this.services.execute(new ClientSessions(client));
           }
       }   

    public static void main(String[]ar) throws Exception{
        Thread t = new Thread(new MySocket());
            t.start();
    }
    }

    //the ClientSession
    public class ClientSessions implements Runnable{

        Socket s;

        public ClientSessions(Socket s){
        this.s = s;    
        }

        DataInputStream dis=null;
        DataOutputStream dos=null;
        boolean success =true;

        @Override
        public void run(){
            //get the data
            try{
            //get inside channels    
            dis = new DataInputStream(this.s.getInputStream());
            //get outside channels
            dos = new DataOutputStream(this.s.getOutputStream());
         //read the name
        //this works
            String name=dis.readUTF();
            String PATH_TO_SAVE ="c://folder//"+name;
                    //now copy file to disk
                   File f = new File(PATH_TO_SAVE);
                    copy(f,dis);
                    //Files.copy(dis,f.toPath());
        //this doesnt print, stuck in the copy(f,dis) method
                    System.out.println("I am done");
                    success =true;
            }catch(Exception ex){
                ex.printStackTrace();
            }finally{
                //clean resources...
               clean();
            }
        }
       //copy from the stream to the disk 
        private void copy(File f,DataInputStream d)throws Exception{
                    f.getParentFile().mkdirs();
                    f.createNewFile();
                    int count =-1;
                    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
                    byte array[] = new byte[1024*8];
                    count =d.read(array);
                    while(count >0){
                        out.write(array,0,count);
                        count =d.read(array);
                        System.out.println("byte out: "+count);
                    }
        //this never prints
                    System.out.println("last read: "+count);
                    out.flush();
                    out.close();
     if(success)dos.writeUTF("Succesful");
                else dos.writeUTF("error");
        }
    } 

//for the clean method i simply have
void clean(){
  if(dis!=null)dis.close();
  if(dos!=null)dos.close();
}

我评论了这个 //Files.copy(dis,f.toPath());从服务器 因为它在将文件写入磁盘后不会进入下一行,有时甚至会卡在那里。

请指点我正确的道路,我相信我在这里做错了什么 不知道这是否有帮助,但客户端在 eclipse 中运行,服务器在 netbeans 中运行

【问题讨论】:

  • 我只删除了它以节省打字时间。我会更新问题以包括它们,谢谢。还有一件事,你的意思是我把 .flush() 放在服务器的 copy() 方法中还是放在客户端的 write() 中,或者两者兼而有之?
  • //clean resources... 有什么?
  • @rustyx 我尝试关闭 dataInputStream 和 DataOutpitStreams。复制(); ClientSession 中的方法在传输数据后不会退出!我按照第一个回复的建议包含了冲洗,但没有任何效果。

标签: java sockets dataoutputstream


【解决方案1】:

想想你的协议:

  • 客户端发送文件名,然后发送二进制文件,然后等待服务器响应。
  • 服务器读取文件名,然后读取二进制文件,直到流关闭,然后发送成功消息。

但是由于客户端正在等待响应,因此流永远不会关闭,因此您的协议中存在死锁。

这通常通过首先发送文件大小并让服务器读取那么多字节来解决。

或者,您可以使用 TCP 的单向关闭功能向服务器发送一个信号,表明套接字的输出流已关闭。这可以通过socc.shutdownOutput(); 完成

请使用try-with-resources 避免资源泄漏(您也必须关闭 Socket)。

固定客户端:

    try {
        System.out.println("File upload started");
        try (Socket socc = new Socket("localhost", 8117);
                DataOutputStream dos = new DataOutputStream(socc.getOutputStream());
                DataInputStream dis = new DataInputStream(socc.getInputStream())) {
            // send file name
            dos.writeUTF(f.getName());
            // send the file
            Files.copy(f.toPath(), dos);
            dos.flush();
            System.out.println("Data has been sent...waiting for server to respond ");
            // signal to server that sending is finished
            socc.shutdownOutput();
            String RESPONSE = dis.readUTF();
            // this never prints prints
            System.out.println("Server sent: " + RESPONSE);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

服务器:

public class MySocket implements Runnable {

    int worker_thread = 2;
    volatile boolean shouldRun = true;
    ServerSocket server;
    int port = 8117;
    ExecutorService services;

    public MySocket() throws IOException {
        this.server = new ServerSocket(port);
        services = Executors.newFixedThreadPool(this.worker_thread);
    }

    // A METHOD TO RUN SERVER THREAD
    @Override
    public void run() {
        while (this.shouldRun) {
            Socket client = null;
            try {
                client = server.accept();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            // hand it over to be processed
            this.services.execute(new ClientSessions(client));
        }
    }

    public static void main(String[] ar) throws Exception {
        new MySocket().run();
    }
}

class ClientSessions implements Runnable {
    Socket s;
    public ClientSessions(Socket s) {
        this.s = s;
    }
    @Override
    public void run() {
        // get the data
        try (DataInputStream dis = new DataInputStream(this.s.getInputStream());
                DataOutputStream dos = new DataOutputStream(this.s.getOutputStream())) {
            // read the name
            // this works
            String name = dis.readUTF();
            String PATH_TO_SAVE = name;
            // now copy file to disk
            File f = new File("c://folder", PATH_TO_SAVE);
            Files.copy(dis, f.toPath());
            dos.writeUTF("Succesful");
            System.out.println("I am done");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

【讨论】:

  • 好的,我已经做到了!那么对于为什么服务器在写入发送给它的文件后没有向客户端发送回消息的任何建议或更正?服务器不打印“最后一个字节”,这意味着它以某种方式卡在了读写操作中。另外,我不应该关闭套接字,因为如果我这样做,它将中止并且不会等待从服务器读取
  • 非常感谢兄弟。你太棒了。
【解决方案2】:

您的代码的问题是,您从套接字的输入流中读取,该输入流永远不会关闭。

DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
byte array[] = new byte[1024*8];
count =d.read(array);
while(count >0){
    out.write(array,0,count);
    count =d.read(array);
    System.out.println("byte out: "+count);
}
//this never prints
System.out.println("last read: "+count);

d.read(array) 正在积极尝试从套接字读取,阻塞直到它收到一些东西。由于 InputStream 是主动阻塞的,它永远不会返回小于或等于 0 的值。这是因为流等待来自 Socket 另一端的下一个包。

发送文件后关闭套接字应该对您有所帮助。在这种情况下,到达 Stream 的末尾并返回 InputStream。

注意:您正在读取的 InputStream 将(如果套接字已关闭)返回 -1,正如您在 JavaDoc 中看到的那样。

在你的情况下,这可能不可行!

您想用“好的”或“错误”来回答客户。如果关闭套接字,则无法通过同一个 Socket 应答。解决方案可能很复杂。

这种情况有点棘手。大多数框架都有一个线程,它从 SocketInputStream 读取并将返回值传递给某种处理程序(在阻塞 IO 中)。您的 while 循环基本上是线程内的主要阅读循环。这个循环只会在连接丢失时退出,因此System.out.println("last read: "+count); 可以更改为System.out.println("disconnected");

为简单起见:您可以估计文件的,然后(仅出于测试目的)编写如下内容:

DataOutputStream out = new DataOutputStream(new 
BufferedOutputStream(new FileOutputStream(f)));
byte array[] = new byte[/* Big enough */ 1024 * 1024 * 8];
d.read(array); // Read the file content
out.write(array); // Write to the file
//this never prints
System.out.println("last read: "+count);

我在这里省略了所有错误检查!这意味着您只能从服务器读取 一个 包,它必须是文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2017-06-09
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多