分类: C/C++
2013-12-10 17:18:15
#define MAX_LINE 100
int main(void)
{
struct sockaddr_in sin;
struct sockaddr_in cin;
int c_fd;
socklen_t len;
char buf[MAX_LINE];
char addr_p[INET_ADDRSTRLEN];
int n;
char str[20]="this is server";
sin.sin_family=AF_INET;
sin.sin_addr.s_addr=INADDR_ANY;
sin.sin_port=htons(PORT);
int l_fd=socket(AF_INET,SOCK_STREAM,0);
bind(l_fd,(struct sockaddr*)&sin,sizeof(struct sockaddr));
listen(l_fd,10);
printf("waiting ...\n");
while(1)
{ //简单的测试了下,当客户端为5,6个的时候,服务端能很好的接受和处理请求。
c_fd=accept(l_fd,(struct sockaddr*)&cin,&len);
memset(buf,0,sizeof(buf));
read(c_fd,buf,MAX_LINE);
printf("content is: %s\n",buf);
write(c_fd,str,20);
printf("send from server: %s\n",str);
close(c_fd);
}
if(close(l_fd)==-1){
perror("fail to close");
exit(1);
}
return 0;
}
客户端:
#define MAX_LINE 100
int main(int argc,char *argv[])
{ struct sockaddr_in sin;
int sfd;
char *str="test sting";
if(argc>1)
str=argv[1];
bzero(&sin,sizeof(struct sockaddr_in));
sin.sin_family=AF_INET;
inet_pton(AF_INET,"130.234.1.110",&sin.sin_addr);
sin.sin_port=htons(SERVER_PORT);
while(1){
if((sfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("fail to creat socket");
exit(1);
}
connect(sfd,(struct sockaddr *)&sin,sizeof(struct sockaddr));
my_write(sfd,str);
my_read(sfd);
sleep(5);
close(sfd);
}
exit(0);
}
void my_read(int fd)
{
char buf[MAX_LINE];
read(fd,buf,MAX_LINE);
printf("recive from server: %s\n",buf);
}
void my_write(int fd,char *buf)
{
printf("send from client: %s\n",buf);
write(fd,buf,strlen(buf)+1);
}