|

楼主 |
发表于 2004-5-8 16:00:19
|
显示全部楼层
完成了
//server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int i,sz,newfd;
char buf[5];
long s,port=80;
struct sockaddr_in sa;
sz=sizeof(sa);
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=INADDR_ANY;
sa.sin_port=htons(80);
buf[0]='h';
buf[1]='e';
buf[2]='l';
buf[3]='l';
buf[4]='o';
s=socket(AF_INET,SOCK_STREAM,0);
//printf("%d\n",s);
i=bind(s,(struct sockaddr*)&sa,sz);
printf("bind值为:%d\n",i);
//printf("%d\n",i);
i=listen(s,1);
printf("listen值为:%d\n",i);
newfd=accept(s,(struct sockaddr *)&sa,&sz);//在收到一个连接之前accept不退出
printf("newfd是%d\n",newfd);
if(newfd!=-1)
{
printf("已经连接!\n\n");
}
sz=-1;
if(sz==-1)
{
sz=recv(newfd,buf,5,0);
}
printf("收到的数据包大小sz:%d",sz);
write(1,buf,5);
return 0;
}
//client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int s,i;
char buf[5];
//long port=80 7797
s=socket(AF_INET,SOCK_STREAM,0);
printf("socket序号为:%d\n",s);
struct sockaddr_in sa;
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=inet_addr("127.0.0.1");
sa.sin_port=htons(80);
i=connect(s,(struct sockaddr *)&sa,sizeof(struct sockaddr));
printf("connet值为%d\n",i);
i=send(s,"hello",5,0);
printf("send值为%d\n",i);
return 0;
}
错误原因:
1.端口号转换成网络格式是16位应该用htons,而htonl转换成了32位
2.在发送和接收阶段都会有一段时间的延时,需要等待
比如用
int sz=-1;//受到的数据大小
while(sz=-1)
{
sz=recv(s,buf,5,0);//recv在接收失败的情况下返回-1
}
:thank |
|