【发布时间】:2012-02-07 05:14:15
【问题描述】:
我只是在学习套接字编程,我正在尝试编写一个 echo 客户端,它从标准输入读取并写入套接字,然后将服务器响应从套接字读取到标准输出。问题是我不知道标准输入会有多长时间或服务器的响应会有多长时间。我尝试使用的代码如下(创建套接字和连接服务器被省略):
length = BUF_SIZE;
while (length == BUF_SIZE) { // length will equal BUF_SIZE if buf is full, when length < BUF_SIZE we have reached an EOF
// Reads from STDIN to buf
if ((length = read(STDIN_FILENO, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error in reading from STDIN");
return 4;
}
// Writes from buf to the socket
if ((write(sock, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error writing to socket");
return 5;
}
}
if ((status = shutdown(sock, 1)) < 0){ // Shuts down socket from doing more receives
fprintf(stderr, "Error shutting down socket for writing");
return 6;
}
length = BUF_SIZE;
while (length == BUF_SIZE){
// Read from socket to buf
if ((length = read(sock, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error reading from socket");
return 7;
}
// Write from buf to STDOUT
if ((write(STDOUT_FILENO, buf, BUF_SIZE)) < 0){
fprintf(stderr, "Error writing to STDOUT");
return 8;
}
}
close(sock);
exit(0);
BUF_SIZE 定义为 100。当我运行我的程序时,程序通常会连接到服务器并发送正确的消息,但它写入 stdout 的内容要么什么都没有,要么是乱码。
我做错了什么?
【问题讨论】:
标签: c sockets tcp client-server