首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DataInputStream挂起读取

DataInputStream挂起读取
EN

Stack Overflow用户
提问于 2016-01-06 18:08:31
回答 1查看 3.4K关注 0票数 1

我有一个套接字客户端,每当我试图从套接字读取输入流时,它就挂起。

代码语言:javascript
复制
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中发送的内容。

,我不明白什么?为什么它在试图读取服务器响应时挂起?

服务器端(处理请求):

代码语言:javascript
复制
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();

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2016-01-06 18:12:50

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

因此,对等方没有关闭连接。

编辑正确地读取您要发送的内容如下:

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

代码语言:javascript
复制
int length = dis.readInt();
byte[] buffer = new byte[length];
dis.readFully(buffer);

但是我会抛出发送和接收代码,并使用readUTF()/writeUTF(),假设数据是字符数据。如果不是,你不应该把它组装成一个字符串。

编辑2证明这是有效的:

Client.java:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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);
            }
        }
    }
}

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34639805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档