如何在使用reader.readLine()和sc.nextLine()

时间:2018-10-23 13:41:17

标签: java sockets blocking

我正在使用reader.readLine()sc.nextLine()模拟服务器和客户端。但是,在扫描仪中输入了一些单词后,服务器什么也没有响应。我认为问题是线程阻塞,但我无法纠正它。任何人都可以指出问题的症结所在。

这是服务器的代码。

public class Server {

    public static LocalDateTime currentTime() {
        return LocalDateTime.now();
    }
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = new ServerSocket(9091);
        System.out.println("TCP server ready.\n");
        Socket sock = ss.accept();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))) {
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))) {
                String cmd;
                System.out.println("read in");
                while ((cmd = reader.readLine()) != null) {
                    System.out.println("Rcvd: " + cmd);
                    if ("time".equals(cmd)) {
                        writer.write(currentTime() + "\n");
                        writer.flush();
                    } else {
                        writer.write("Sorry?\n");
                        writer.flush();
                    }   
                }    
            }
        }
        sock.close();
        ss.close();

    }

}

客户代码

public class Client {

    public static void main(String[] args) throws IOException, InterruptedException {
        InetAddress addr = InetAddress.getLoopbackAddress();
        try (Socket sock = new Socket(addr, 9091)){
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))){
                try (BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))){
                    Scanner sc = new Scanner(System.in);
                    String cmd;
                    while (sc.hasNext()) {
                        cmd = sc.nextLine();
                        System.out.println("Scanned: " + cmd);
                        writer.write(cmd);
                        writer.flush();

                        String resp = reader.readLine();
                        System.out.println("Response: " + resp);
                    }

                }
            }
        }

1 个答案:

答案 0 :(得分:1)

在客户端中使用它:

writer.write(cmd + "\n");

因为服务器读取了行。