|
楼主 |
发表于 2009-10-27 09:55:51
|
显示全部楼层
server.c
=======================================
int port = 8800;
int main(void)
{
struct sockaddr_in sock_addr_send ;
struct sockaddr_in sock_addr_rece ;
int mysock;
int tempsock;
int addrsize;
char str[100],str1[20],str2[20],str3[20] ;
char buf[100]={"i have received the info "};
int i ,len1,len2;
float c;
// 建立socket
mysock = socket(AF_INET,SOCK_STREAM,0);
if(mysock<0)
{
perror("create socket failed ......");
exit(1);
}
// 建立本机IP地址
bzero(&sock_addr_send,sizeof(sock_addr_send));
sock_addr_send.sin_family = AF_INET;
// sock_addr_send.sin_addr.s_addr = htonl(INADDR_ANY);
sock_addr_send.sin_addr.s_addr = inet_addr("127.0.0.1");
sock_addr_send.sin_port = htonl(port);
// 绑定socket
if(bind(mysock,(struct sockaddr*)&sock_addr_send,sizeof(sock_addr_send))<0)
{
perror("bind error ......");
exit(1);
}
// 监听client
if(listen(mysock,10)<0)
{
perror("listen failed ......");
exit(1);
}
printf("waiting connecting .....................................\n");
while(1)
{
tempsock = accept(mysock,(struct sockaddr*)&sock_addr_rece,&addrsize);
if(tempsock<0)
{
perror("tempsock failed ......");
exit(1);
}
len1= recv(tempsock,str,100,0);
printf("收到的字节数目: %d\n",len1);
str[len1] = '\0';
printf("收到的字符串是: %s\n",str);
len2 = strlen(buf);
if(send(tempsock,buf,len2,0)<0)
{
perror("send info failed......");
exit(1);
}
close(tempsock);
}
return 0;
}
===============================================
client.c
int port = 8800;
int main (void)
{
struct sockaddr_in pin;
int mysock;
char buf[8192];
char* str = "i want connect server ......";
bzero(&pin, sizeof(pin));
pin.sin_family = AF_INET;
// pin.sin_addr.s_addr = htonl(INADDR_ANY);
pin.sin_addr.s_addr = inet_addr("127.0.0.1");
pin.sin_port = htons(port);
mysock = socket(AF_INET,SOCK_STREAM,0);
if(mysock<0)
{
perror("socket failed ......");
exit(1);
}
if(connect(mysock,(struct sockaddr *)&pin,sizeof(pin))<0)
{
perror("connect failed .....");
exit(1);
}
printf("send message to server : %s \n",str);
if(send(mysock,str,strlen(str),0)<0)
{
perror("send failed.....");
exit(1);
}
if(recv(mysock,buf,8192,0)<0)
{
perror("recv failed .....");
exit(1);
}
printf("recv message from server : %s \n",buf);
close(mysock);
return 0;
} |
|