【问题标题】:DataInputStream hangs on readDataInputStream 在读取时挂起
【发布时间】:2016-01-06 18:08:31
【问题描述】:

每当我尝试从套接字读取输入流时,我的套接字客户端就会挂起。

DataInputStream dis = new DataInputStream(socket.getInputStream());

int singleByte;
while((singleByte = dis.read()) != -1) {  //<-- hangs here
    char c = (char)singleByte;                     
    // append character
    message_string += c;                        
}
  • 挂在while((singleByte = dis.read()) != -1) {

我已确认服务器正在回显我以原始 ASCII 发送的内容。

我不明白什么?为什么尝试读取服务器响应时挂起?

服务器端(处理请求):

class HandleInputBuffer implements Runnable {

    private String msg = "";
    private String response = "8"; 

    public HandleInputBuffer(String str) {
        this.msg = str;
    }

    @Override
    public void run() {

        String exception_msg = "";

        // process incoming message
        try {
            if(msg!=null){
                if(msg.length()>0){

                    // create and send reply
                    String response = "8"; 

                    // ****************************
                    // create and send response
                    // ****************************
                    try {

                        response = msg;
                        output_stream = new DataOutputStream(client_socket.getOutputStream());
                        output_stream.writeInt(response.getBytes("US-ASCII").length);
                        output_stream.write(response.getBytes("US-ASCII")); 
                        output_stream.flush();                          
                        output_stream.close();

                        //client_socket.shutdownOutput();
                        client_socket.close();


                    } catch (IOException e) {
                        e.printStackTrace();
                        try{output_stream.flush();} catch (IOException e1) {}
                        try {client_socket.close();} catch (IOException e1) {}
                        try {updateConversationHandler = new Handler();} catch (Exception e1) {}

                        return;
                    } 

                }

            }
        } catch (Exception e) {             
            e.printStackTrace();                
        }

    }

}

客户端重构 - 此代码挂起 int length = dis.readInt();

InetAddress serverAddr = InetAddress.getByName(edit_ip_address.getText().toString());

if(socket == null){         
     socket = new Socket(serverAddr, Integer.parseInt(edit_port.getText().toString()));         
}

// send bytes
output_stream = new DataOutputStream(socket.getOutputStream());                        
output_stream.write(command.getBytes("US-ASCII"));

DataInputStream dis = new DataInputStream(socket.getInputStream());

int length = dis.readInt();
byte[] buffer = new byte[length];  //<-- OutOfMemoryException
dis.readFully(buffer);
for (byte b:buffer){
     char c = (char)b;  
     message_string += c;
}

【问题讨论】:

  • @Kayaman 是的,输出流在写入后立即被刷新。
  • um .... 你的例子没有编译,DataInputStream#read 需要一个参数
  • @specializt 嗯,不,它没有:有三个重载,分别有零、一个和三个参数。
  • @specializt - 我对编译没有任何问题。我的代码编译得很好——这就是我知道它正在读取的方式。我不知道还能告诉你什么。
  • @specializt 是的:检查从FilterInputStream. 继承的方法你应该阅读你的链接而不是假设事情。也没有弃用的 API。

标签: java datainputstream


【解决方案1】:

此循环将阻塞,直到对等方关闭连接。

Ergo 对等端没有关闭连接。

编辑阅读您发送的内容的正确方法如下:

您需要读取您正在编写的整数长度字。它不会通过available():神奇地出现

int length = dis.readInt();
byte[] buffer = new byte[length];
dis.readFully(buffer);

但我会丢弃发送和接收代码并使用readUTF()/writeUTF(),假设数据是字符数据。如果不是,则不应将其组装为字符串。

EDIT 2 证明此方法有效:

Client.java:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client
{
    public static void  main(String[] args) throws IOException
    {
        try (Socket s = new Socket("localhost", 9999))
        {
            DataOutputStream    out = new DataOutputStream(s.getOutputStream());
            out.writeInt(1);
            out.writeBytes("8");
            DataInputStream in = new DataInputStream(s.getInputStream());
            int count = in.readInt();
            System.out.println("Reading "+count+" bytes");
            byte[] buffer = new byte[count];
            in.readFully(buffer);
            System.out.write(buffer, 0, count);
            System.out.println();
        }
    }
}

Server.java:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{
    public static void  main(String[] args) throws IOException
    {
        try (ServerSocket ss = new ServerSocket(9999))
        {
            try (Socket s = ss.accept())
            {
                DataInputStream in = new DataInputStream(s.getInputStream());
                int count = in.readInt();
                System.out.println("Reading "+count+" bytes");
                byte[] buffer = new byte[count];
                in.readFully(buffer);
                System.out.write(buffer, 0, count);
                System.out.println();
                DataOutputStream    out = new DataOutputStream(s.getOutputStream());
                out.writeInt(count);
                out.write(buffer, 0, count);
            }
        }
    }
}

如果你没有,你正在从套接字读取其他内容,或者向其中写入其他内容,或者没有运行你认为正在运行的代码。

【讨论】:

  • 客户端不应该关闭连接吗?
  • 我不知道。你没有提到或描述你的协议。如果您不希望对等方必须关闭连接,请不要读取到流的末尾。
  • 在服务器上关闭套接字没有区别。它仍然挂起。
  • 这根本不可能。再试一次。
  • 请查看我的编辑 - 使用服务器端代码,我在客户端得到完全相同的行为。
猜你喜欢
  • 1970-01-01
  • 2021-12-23
  • 2023-04-11
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 2018-10-26
相关资源
最近更新 更多