Chinaunix首页 | 论坛 | 博客
  • 博客访问: 317335
  • 博文数量: 113
  • 博客积分: 446
  • 博客等级: 下士
  • 技术积分: 1229
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-09 16:01
个人简介

Let's go!!!!!

文章分类

全部博文(113)

文章存档

2019年(5)

2018年(4)

2017年(9)

2016年(5)

2015年(39)

2014年(6)

2013年(28)

2012年(17)

分类: LINUX

2013-01-21 17:47:17

//server.c

#include
#include
#include
#include
#include
#include
#include
#include
#include

#define exit_err(str) do{perror(str);exit(1);}while(0);
#define port  5555

int main()
{
struct sockaddr_in addr1,addr2;
int sockfd_server,sockfd_client;
int lisnum=5;
char buf[1024];
socklen_t len;
int reuse;

bzero(&addr1,sizeof(addr1));
addr1.sin_family=AF_INET;
addr1.sin_port=htons(port);
addr1.sin_addr.s_addr=INADDR_ANY;

if((sockfd_server=socket(AF_INET,SOCK_STREAM,0))==-1)
exit_err("socket error");

len=sizeof(struct sockaddr);
if(bind(sockfd_server,(struct sockaddr *)&addr1,len)==-1)
exit_err("bind error");

if(listen(sockfd_server,lisnum)==-1)
exit_err("listen error");

printf("Server wait accept!!!\n");
if((sockfd_client=accept(sockfd_server,(struct sockaddr *)&addr2,&len))==-1)
exit_err("accept error");
printf("Have got communcation!!!\n");

setsockopt(sockfd_server,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(int));
setsockopt(sockfd_client,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(int));

while(1)
{
bzero(buf,sizeof(buf));
printf("Send:");
gets(buf);
if(!bcmp(buf,"quit",4))
{
if(send(sockfd_client,"Server over",sizeof(buf),0)==-1)
exit_err("send error");
printf("Server Over\n");
close(sockfd_client);
break;
}
if(send(sockfd_client,buf,sizeof(buf),0)==-1)
exit_err("send error");

bzero(buf,sizeof(buf));
if(recv(sockfd_client,buf,sizeof(buf),0)==-1)
exit_err("recv error");
if(!bcmp(buf,"Client over",11))
{
printf("Server over\n");
close(sockfd_client);
break;
}
printf("Recieved:%s\n",buf);
}

close(sockfd_server);
return 0;
}

//client.c

#include
#include
#include
#include
#include
#include
#include
#include
#include

#define exit_err(str) do{perror(str);exit(1);}while(0);
#define port 5555

int main()
{
struct sockaddr_in addr1;
char buf[1024];
int sockfd;
socklen_t len;

bzero(&addr1,sizeof(addr1));
addr1.sin_family=AF_INET;
addr1.sin_port=htons(port);
addr1.sin_addr.s_addr=inet_addr("10.224.73.227");

if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
exit_err("socker error");

if(connect(sockfd,(struct sockaddr *)&addr1,sizeof(addr1))==-1)
exit_err("connect error");
printf("connection ready!!!\n");

while(1)
{
bzero(buf,sizeof(buf));
if(recv(sockfd,buf,sizeof(buf),0)==-1)
exit_err("recv error");
if(!bcmp(buf,"Server over",11))
{
printf("Client over\n");
break;
}
printf("Recieved:%s\n",buf);

printf("Send:");
gets(buf);
if(!bcmp(buf,"quit",4))
{
if(send(sockfd,"Client over",sizeof(buf),0)==-1)
exit_err("send error");
printf("Client over\n");
break;
}
if(send(sockfd,buf,sizeof(buf)-1,0)==-1)
exit_err("send error");
}
close(sockfd);
return 0;
}

 

阅读(451) | 评论(0) | 转发(0) |
0

上一篇:C语言,串操作

下一篇:异步通信

给主人留下些什么吧!~~