Let's go!!!!!
分类: 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;
}