java - 从 Socket 读取时卡在写操作中

标签 java sockets dataoutputstream

我正在通过 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 中运行

最佳答案

想想你的协议(protocol):

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

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

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

    或者,您可以使用 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();
                }
            }
        }
    
    }
    

    关于java - 从 Socket 读取时卡在写操作中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53836574/

    相关文章:

    java - 如何在selenium java中以相反的顺序打印 anchor 标记及其Web元素的值?

    java - XStream:使用 XStreamImplicit 省略集合

    python - 将 Python 对象传递给另一个 Python 进程

    C 套接字双栈 ss_family 始终 IPv6

    java - 有趣的 Java 正则表达式限制

    java - 二叉搜索树的搜索和比较内容的大O

    c++ - 发出 double over TCP 套接字的发送/接收 vector (丢失数据)

    java - DataOutputStream 和 printwriter 有什么区别?

    java - 向服务器发送 POST 请求