Java - 从缓冲读取器(从套接字)读取正在暂停线程

问题描述 投票:0回答:5

我有一个线程从缓冲读取器读取字符(从套接字创建,如下所示):

inputStream = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));

此代码只能运行一次。例如,如果客户端连接并发送以下内容: “这是一个测试”和“这是另一个测试”,主机输出是:

 Reading from stream:
 Chars read from stream: 16
 This is a test

 Reading from stream:

请注意,程序不会收到“这是另一个测试”,因为它停留在读取流上。有没有办法在不减少缓冲区大小的情况下处理这个问题? 这是线程的代码:

public void run() {
        boolean dataRecieved = false;
        char[] inputChars = new char[1024];
        int charsRead = 0;

        while (!stopNow) {

            try {
                Thread.sleep(getDataDelay);

                //Read 1024 characters. Note: This will pause the thread when stream is empty.
                System.out.println("Reading from stream:");
                charsRead =  inputStream.read(inputChars); //<< THIS LINE IS PAUSING THE THREAD!> 


                if ((charsRead =  inputStream.read(inputChars)) != -1)
                {
                    System.out.println("Chars read from stream: " + charsRead);  
                    System.out.println(inputChars);
                    System.out.flush();
                }


            } catch (IOException e) {
                System.out.println("IOException");
                //TODO: CLIENT HAS DISCONNECTED...
            } catch (InterruptedException e) {
                System.out.println("Interrupted");
                // Sleep was interrupted.
            } 

        }

    }

客户端/发件人代码(不是我的代码):

public static void main(String[] args) throws IOException {
        // <<<<<<<<<<< CLIENT >>>>>>>>>>>>>>>

        Socket sock = new Socket("127.0.0.1", 3000);
        // reading from keyboard (keyRead object)
        BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
        // sending to client (pwrite object)
        OutputStream ostream = sock.getOutputStream(); 
        PrintWriter pwrite = new PrintWriter(ostream, true);

        // receiving from server ( receiveRead  object)
        InputStream istream = sock.getInputStream();
        BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

        System.out.println("Start the chitchat, type and press Enter key");

        String receiveMessage, sendMessage;               
        while(true)
        {
            sendMessage = keyRead.readLine();     // keyboard reading
            pwrite.println(sendMessage);       // sending to server
            System.out.flush();         // flush the data

            if((receiveMessage = receiveRead.readLine()) != null) //receive from server
            {
                System.out.println(receiveMessage); // displaying at DOS prompt
            }         
        }               
    }          
java sockets networking buffer
5个回答
13
投票

java.io.InputStream.read()
是一个阻塞调用,这意味着如果没有可用数据,线程将暂停,直到数据可用。

对于非阻塞 I/O,请使用

java.nio
包中的类。


3
投票

您的“发送者”正在等待从“接收者”接收返回的数据,这就是代码无限期等待的地方。接收方收到消息后是否应该发送响应?


1
投票
Socket socket;

// Assuming socket is connected and not null

if(socket != null){
    if(socket.getInputStream().available() > 0){
        byte[] buffer;
        buffer = new byte[socket.getInputStream().available];
        socket.getInputStream().read(buffer);

        // Your code here to deal with buffer.

    }
}

如果你想写入套接字,

OutputStream mmOutStream;
mmOutStream = socket.getOutputStream();

public void write(byte[] buffer) {
    try {
        mmOutStream.write(buffer);
    } catch (IOException e) {
        Log.e(TAG, "Exception during write ", e);
    }
}

0
投票

实现一个协议,在标头中发送数据长度,以便服务器/客户端知道需要多少数据。


-1
投票

您必须创建

ServerSocket
在每个循环中监听客户端。

ServerSocket socket = new ServerSocket(3000);

这是我的 run() 方法,每次都会等待客户端

Socket

public void run(){
        boolean dataRecieved = false;
        char[] inputChars = new char[1024];
        int charsRead = 0;

        while (!stopNow) {
            try {
                System.out.println("Listen To Clients:");

                // The ServerSocket has to listen the client each time.
                InputStreamReader isr = new InputStreamReader( socket.accept().getInputStream() );
                inputStream = new BufferedReader( isr );

                //Read 1024 characters. Note: This will pause the thread when stream is empty.
                System.out.println("Reading from stream:");

                if ((charsRead =  inputStream.read(inputChars)) != -1)
                {
                    System.out.println("Chars read from stream: " + charsRead);  
                    System.out.println(inputChars);
                    System.out.flush();
                }
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }

您还有另一个小错误,它会停止代码并删除该行

charsRead =  inputStream.read(inputChars); //<< THIS LINE IS PAUSING THE THREAD!>

因为这一行是在

if
语句中移动的。

© www.soinside.com 2019 - 2024. All rights reserved.