英文:
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("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.
}
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论