【发布时间】:2013-12-03 00:24:18
【问题描述】:
当我运行这个程序时,我输入一个 IP 地址和服务器端口作为输入。但是,在此之后程序要求我“请输入味精:”。但是,在输入我的消息后,按 ctrl-D 不会执行任何操作。程序仍然从 STDIN 读取。如何指示我正在输入的消息的结尾?
这是我正在使用的程序:
/*
* echoclient.c - A simple connection-based client
* usage: echoclient <host> <port>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUFSIZE 1024
/*
* error - wrapper for perror
*/
void error(char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char **argv) {
int sockfd, portno, n;
struct sockaddr_in serveraddr;
struct hostent *server;
char *hostname;
char buf[BUFSIZE];
/* check command line arguments */
if (argc != 3) {
fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]);
exit(0);
}
hostname = argv[1];
portno = atoi(argv[2]);
/* socket: create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
/* gethostbyname: get the server's DNS entry */
server = gethostbyname(hostname);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host as %s\n", hostname);
exit(0);
}
/* build the server's Internet address */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(portno);
/* connect: create a connection with the server */
if (connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
error("ERROR connecting");
/* get message line from the user */
printf("Please enter msg: ");
bzero(buf, BUFSIZE);
fgets(buf, BUFSIZE, stdin);
/* write: send the message line to the server */
n = write(sockfd, buf, strlen(buf));
if (n < 0)
error("ERROR writing to socket");
/* read: print the server's reply */
bzero(buf, BUFSIZE);
n = read(sockfd, buf, BUFSIZE);
if (n < 0)
error("ERROR reading from socket");
printf("Echo from server: %s", buf);
close(sockfd);
return 0;
}
【问题讨论】:
-
看起来程序应该停止读取
stdin,只要您在消息的第一行末尾点击“enter”。是什么让您认为它仍在读取输入? -
如果我按下回车键,它只会转到下一行并继续接受更多输入。
-
我怀疑该程序已经转到
n = read(sockfd, buf, BUFSIZE)并正在等待从服务器获得响应,同时没有收听来自键盘的输入。此时您可以在键盘上键入任何您想要的内容,包括 Ctrl-D,但程序不会注意到它,直到read调用返回。 -
如果我想要来自服务器的响应,我是在客户端之前运行服务器程序还是在服务器之前运行客户端?
-
如果你在启动服务器之前运行客户端程序,那么客户端将没有任何东西可以连接:-)