为什么我不能在没有换行符的情况下运行这段TCP客户端套接字代码?

huangapple go评论81阅读模式
英文:

Why can't I run this tcp client socket code without \n?

问题

以下是您提供的代码的翻译部分:

我尝试了这段代码它正常工作但如果我在`String str`中删除`\n`,它就无法正常工作我的意思是如果在没有`\n`的情况下能够编译通过但却没有给我输出

public class Test {
    // 使用try-with-resources关闭套接字。
    public static void main(String args[]) throws Exception {
        int c;
        // 创建一个连接到internic.net,端口为43的套接字。使用try-with-resources块管理此套接字。
        try (Socket s = new Socket("whois.internic.net", 43)) {
            // 获取输入和输出流。
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            // 构造请求字符串。
            String str = (args.length == 0 ? "MHProfessional.com" : args[0]) + "\n"; // <- 这里
            // 转换为字节。
            byte buf[] = str.getBytes();
            // 发送请求。
            out.write(buf);
            // 读取并显示响应。
            while ((c = in.read()) != -1) {
                System.out.print((char) c);
            }
        }
        // 套接字现已关闭。
    }
}
英文:

I was trying this code. it works fine but if I remove \n in String str it doesn't work I mean It was able to compile without \n but it didn't give me output.

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(&quot;whois.internic.net&quot;, 43)) {
            // Obtain input and output streams.
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            // Construct a request string.
            String str = (args.length == 0 ? &quot;MHProfessional.com&quot; : args[0]) + &quot;\n&quot;; // &lt;- 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.
    }
}

答案1

得分: 1

与您通话的服务器会读取数据,直到遇到换行(\n)字符为止 -- 这就是它的工作方式,但这并不罕见。其他换行序列也可能会被接受。

服务器必须有某种方式来知道客户端何时完成了数据发送。如果客户端关闭了连接,服务器可能会知道,但到那时已经太迟回复客户端了。

英文:

The server you're talking to reads data up until an end-of-line (\n) character -- that's just the way it works, but it's far from unusual. It's possible that other end-of-line sequences will be accepted as well.

The server has to have some way to know the client has finished sending data. It will probably know if the client closes its connection, but by then it's too late to respond to the client.

huangapple
  • 本文由 发表于 2020年9月17日 12:10:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63931146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定