该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
服务器端程序如下:
#include"stdio.h"
#include"sys/socket.h"
#include"netdb.h"
#define IP "127.0.0.1"
#define PORT 300
int main()
{
char msg[50];
struct sockaddr_in ad;
int s,len,adlen,news;
if((s=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("error!");
}
else
{
printf("Socket Created!\n");
printf("Socket:%d\n",s);
}
bzero(&ad,sizeof(ad));
ad.sin_port=htons(PORT);
ad.sin_addr.s_addr=inet_addr(IP);
ad.sin_family=AF_INET;
len=sizeof(msg);
adlen=sizeof(struct sockaddr_in);
if(bind(s,(struct sockaddr *)&ad,adlen)<0)
printf("error!");
else
printf("Have binded!\n");
if(listen(s,3)<0)
perror("listen");
else
printf("listen.........\n");
if( (news=accept(s,(struct sockaddr *)&ad,&adlen) )<0 )
perror("accept");
else
printf("have accepted!\n");
while(1)
{
bzero(msg,len);
recv(news,msg,len,0);
printf("Receve:%s",msg);
send(news,msg,len,0);
}
}
客户端程序如下:
#include"stdio.h"
#include"sys/socket.h"
#include"netdb.h"
#include"unistd.h"
#define IP "127.0.0.1"
#define PORT 300
int main()
{
char msg[20];
struct sockaddr_in ad;
int s,len,adlen,i=0;
if((s=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("error!");
}
else
printf("Socket Created!\n");
bzero(&ad,sizeof(ad));
ad.sin_port=htons(PORT);
ad.sin_addr.s_addr=inet_addr(IP);
ad.sin_family=AF_INET;
len=sizeof(msg);
adlen=sizeof(struct sockaddr_in);
if(connect(s,(struct sockaddr *)&ad,adlen)<0)
printf("error!");
else
printf("Have Connected!\n");
while(1)
{
bzero(msg,len);
len=read(STDIN_FILENO,msg,sizeof(msg));
send(s,msg,len,0);
recv(s,msg,len,0);
printf("Receve:%s\n",msg);
}
}
问题:为什么客户端向服务器发送字符串时,服务器可以收到。但是客户机只第一次能收到服务器返回的字符串,以后就无法收到服务器返回的字符串?