我写了一些代码在C中的TCP服务器,回声无论它得到。问题在于,当我第一次发送数据时会回应它,并在下次服务器发回我发送的第一个数据包。日志是这样的:TCP回声服务器,只回声的第一个数据包(C语言)
Client Send : Packet1
Server reply : Packet1
Client Send : Packet2
server reply : Packet1
服务器代码如下:
int main(int argc, char** argv) {
int listenfd,connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in servaddr,cliaddr;
listenfd = socket(AF_INET,SOCK_STREAM,0);
printf("Socket listenfd : %d with %d And %d\n",listenfd,AF_INET,SOCK_STREAM);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
printf("Server address: %d\n",servaddr.sin_addr.s_addr);
bind(listenfd, (SA*) &servaddr, sizeof(servaddr));
printf("Listened: %d\n",listenfd);
listen(listenfd,LISTENQ);
printf("After Listening: %d\n",listenfd);
int num=0;
for(; ;){
clilen=sizeof(cliaddr);
connfd = accept(listenfd, (SA*) &cliaddr,&clilen);
printf("Client no. %d connected\n",++num);
if((childpid=fork())==0){
close(listenfd);
echo(connfd);
exit(0);
printf("Client no. %d Terminated\n",++num);
}
close(connfd);
}
return (EXIT_SUCCESS);
}
我的回声功能:
void echo(int sockfd) {
ssize_t n;
char buf[MAXLINE];
again:
while ((n = read(sockfd, buf, MAXLINE)) > 0)
writen(sockfd, buf, n);
if (n < 0 && errno == EINTR)
goto again;
else if (n < 0)
printf("read error");
}
客户端代码主:
int main(int argc, char** argv) {
int sockfd;
struct sockaddr_in servaddr;
sockfd= socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port= htons(SERV_PORT);
inet_pton(AF_INET,"0.0.0.0",&servaddr.sin_addr);
printf("%d , %d \n",sockfd,servaddr.sin_addr.s_addr);
connect(sockfd, (SA*) &servaddr,sizeof(servaddr));
printf("%d\n",sockfd);
replyBack(stdin,sockfd);
printf("RETURN\n");
return (EXIT_SUCCESS);
}
replyBack功能:
void replyBack(FILE *fp, int sockfd) {
char sendline[MAXLINE], recvline[MAXLINE];
printf("ENTER YOUR ECHOED: \n");
while (fgets(sendline, MAXLINE, stdin) != NULL) {
write(sockfd, sendline, sizeof(sendline));
if (read(sockfd, recvline, MAXLINE) == 0)
{
printf("str_cli: server terminated prematurely");
exit(-1);
}
fputs(recvline, stdout);
}
}
+0
你的客户端和服务器对我来说工作得很好。检查以确保您所做的任何系统调用('read','write','connect'等)都返回错误或小于预期的值。尝试使用Wireshark来查看实际上通过网络发送的内容,这会告诉您问题出在客户端还是服务器上。尝试使用'netcat'作为替代客户端。 –
2011-03-02 18:43:55
+0
THANKs :)我会尝试使用它们 –
2011-03-02 19:22:44