java.net.Socket> InputStream> BufferedReader.read(char [])阻塞线程

时间:2015-03-09 20:43:55

标签: java multithreading sockets tcp deadlock

我尝试使用BufferedReader.read(char [])方法而不是更简单但功能较少的BufferedReader.readLine()方法来接收来自服务器的答案。 BufferedReader与BufferedOutputStream并行使用,在下面的代码中,read(char [])方法阻塞所有内容,最后一个控制台输出是" 新缓冲区,等待读取。&# 34;

客户端:

public class MessageSender extends Thread {
private String message;
MessageSender(String message) {
    this.message = message;
}

public void run() {
    try {
        Socket sk = new Socket("192.168.1.4", 3000);
        BufferedOutputStream bo = new BufferedOutputStream(sk.getOutputStream());
        bo.write(message.getBytes());
        bo.flush();

        char[] c = new char[100];

        BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
        StringBuffer sb = new StringBuffer();
        System.out.println("new buffer, waiting to read.");
        int ix = 0;

        while (ix != -1) {
            ix = br.read(c);
            sb.append(new String(c));
        }

        String message = sb.toString();

        System.out.println("reply: " + message);

        sk.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

服务器:

public class MessageReceiver extends Thread {
    public void run() {
        try {
            ServerSocket ss = new ServerSocket(3000);
            System.out.println("server socket open");
            while (true) {
                Socket sk = ss.accept();
                System.out.println("new connection");
                BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                String line = br.readLine();
                System.out.println("received line: " + line);
                BufferedOutputStream bo = new BufferedOutputStream(sk.getOutputStream());
                bo.write("ack".getBytes()); bo.flush(); //bo.close();
                sk.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

主:

public class Main {

    public static void main(String[] args) {
        MessageReceiver mr = new MessageReceiver();
        mr.start();
        while (true) {
            String msg = new Scanner(System.in).nextLine();
            MessageSender ms = new MessageSender(msg+"");
            ms.start();
        }
    }
}

只要未调用BufferedReader.read,一切正常。但是由于代码现在是正确的,输出似乎不会被发送到服务器。

更新

正如@JB Nizet所回答的,问题在于使用readLine()的服务器脚本并等待EOL字符或连接端。因此,添加" \ n"从客户端发送的消息解决了死锁:

bo.write((message+"\n").getBytes());

1 个答案:

答案 0 :(得分:2)

当服务器接受来自客户端的连接时,它首先做的是:

String line = br.readLine();

因此,它会阻塞,直到客户端发送完整的文本行。如果服务器读取EOL字符,或者客户端关闭了流,则服务器只知道该行已完成。

当客户端启动时,它首先要做的是

bo.write(message.getBytes());

message是一行文字,没有任何EOL。然后客户端

ix = br.read(c);

所以它等待来自服务器的响应,服务器本身正在等待来自客户端的EOL。

您已实施网络死锁。