从 DataOutputStream 重新分配给 BufferedOutputStream 和 FileOutputSt



我在使用 writeUTF("字符串")通过套接字交谈时遇到问题,客户端使用 readUTF() 侦听消息。
到目前为止,它按照我的意愿工作。 但是,在添加从客户端接收文件的代码后,我无法向客户端发送任何按摩。 代码如下。 已经有好几天了... 谁能帮我解决这个问题? 感谢您的投入:-)

客户端.java

            String ack = in.readUTF();
            println(ack); // "How do you do?"
            String aack = in.readUTF();
            println(aack); // HANGING FOREVER

服务器.java

                Socket server        = serverSocket.accept();
                DataInputStream in   = new DataInputStream(server.getInputStream());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());


// CAN SEND MESSAGES    
                out.writeUTF("How do you do? "+ "rn");
                out.flush();
// AFTER THIS SEGMENT CANNOT WRITE TO CLIENT ANYMORE
                    int bytesRead;
                    int current              = 0;
                    FileOutputStream fos     = null;
                    BufferedOutputStream bos = null;
                    try {
                        byte [] byteArray = new byte [FILE_SIZE];
                        InputStream is    = server.getInputStream();
                        fos               = new FileOutputStream(FILE_TO_RECEIVED);
                        bos               = new BufferedOutputStream(fos);
                        bytesRead         = is.read(byteArray,0,byteArray.length);
                        current           = bytesRead;
                        do {
                            bytesRead =
                                    is.read(byteArray, current, (byteArray.length-current));
                            if(bytesRead >= 0) current += bytesRead;
                        } while(bytesRead > -1);
                        bos.write(byteArray, 0 , current);
                        bos.flush();
                        System.out.println("File " + FILE_TO_RECEIVED
                                + " downloaded (" + current + " bytes read)");
                    }
        finally {
            if (fos != null) fos.close();
            if (bos != null) bos.close();
        }
// WORKS ALRIGHT UP TO THIS PART
// PROBLEM BEGINS...
// CANNOT                 
// SEND MASSAGE ANYMORE  
// CLIENT WAIT FOR MSG HANGING FOREVER 
             out.writeUTF("Can you hear?"+ "rn");
             out.flush();

我建议您使用OutputStreamWriter,例如

OutputStream out = ...;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "utf-16"));

相关内容

  • 没有找到相关文章

最新更新