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

时间:2011-06-13 08:23:30

标签: java sockets networking buffer

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

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
            }         
        }               
    }          

5 个答案:

答案 0 :(得分:10)

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

对于非阻塞I / O,请使用java.nio包中的类。

答案 1 :(得分:2)

您的“发件人”正在等待从“接收器”接收数据,这是代码无限期等待的地方。收件人是否应该在收到消息时发送响应?

答案 2 :(得分:0)

实施一个协议,您可以在标题中发送数据长度,以便服务器/客户端知道预期的数据量。

答案 3 :(得分:0)

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);
    }
}

答案 4 :(得分:-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语句中移动。