【问题标题】:Why can't I run this tcp client socket code without \n?为什么我不能在没有 \n 的情况下运行这个 tcp 客户端套接字代码?
【发布时间】:2020-09-17 04:10:54
【问题描述】:

我正在尝试此代码。它工作正常,但如果我在 String str 中删除 \n 它不起作用我的意思是它能够在没有 \n 的情况下编译,但它没有给我输出。

public class Test {
    // Use try-with-resources to close a socket.
    public static void main(String args[]) throws Exception {
        int c;
        // Create a socket connected to internic.net, port 43. Manage this
        // socket with a try-with-resources block.
        try (Socket s = new Socket("whois.internic.net", 43)) {
            // Obtain input and output streams.
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            // Construct a request string.
            String str = (args.length == 0 ? "MHProfessional.com" : args[0]) + "\n"; // <- herer
            // Convert to bytes.
            byte buf[] = str.getBytes();
            // Send request.
            out.write(buf);
            // Read and display response.
            while ((c = in.read()) != -1) {
                System.out.print((char) c);
            }
        }
        // The socket is now closed.
    }
}

【问题讨论】:

  • 服务器可能使用\n 作为指示它应该读取的内容量

标签: java string sockets tcpsocket


【解决方案1】:

您正在与之交谈的服务器会一直读取数据,直到出现行尾 (\n) 字符——这正是它的工作方式,但并不罕见。其他行尾序列也可能会被接受。

服务器必须有一些方法来知道客户端已经完成发送数据。它可能会知道客户端是否关闭了它的连接,但是到那时响应客户端已经太晚了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    相关资源
    最近更新 更多