2014年(41)
分类: LINUX
2014-05-10 00:36:11
SERVER:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
void *do_client(void *arg);
int main(int argc,char **argv)
{
int servfd;
int ret;
pthread_t tid;
//调用socket函数创建套接字。
servfd = socket(AF_INET,SOCK_STREAM,0);
if(-1 == servfd)
{
perror("socket");
return -1;
}
//填充地址信息(服务器)
struct sockaddr_in servaddr;
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(7777);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
socklen_t len = sizeof(servaddr);
ret = bind(servfd,(struct sockaddr *)&servaddr,len);
if(-1 == ret)
{
perror("bind");
return -1;
}
//调用listen启动监听
ret = listen(servfd,100);
if(-1 == ret)
{
perror("listen");
return -1;
}
int clifd;
struct sockaddr_in cliaddr;
while(1)
{
memset(&cliaddr,0,sizeof(cliaddr));
clifd = accept(servfd,(struct sockaddr *)&cliaddr,&len);
if(-1 == clifd)
{
perror("accept");
return -1;
}
printf("%d is connect success......\n",clifd);
printf("ip : %s\n",inet_ntoa(cliaddr.sin_addr));
printf("port: %d\n",ntohs(cliaddr.sin_port));
ret = pthread_create(&tid,NULL,do_client,&clifd);
if(0 != ret)
{
perror("pthread_create");
return -1;
}
pthread_detach(tid);
}
//调用close关闭连接。
close(servfd);
close(clifd);
return 0;
}
void *do_client(void *arg)
{
int clifd;
int ret;
char buf[102] = {0};
clifd = *(int *)arg;
while(1)
{
memset(buf,0,sizeof(buf));
ret = read(clifd,buf,sizeof(buf)-1);
if(ret > 0)
{
printf("recv message:%s\n",buf);
write(clifd,"HI\n",strlen("HI\n"));
}
}
return (void *)0;
}
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFSZ 1024
int main(void)
{
int clifd;
int ret;
char buf[BUFSZ] = {0};
struct pollfd pfd[2] = {0};
//调用socket函数创建套接字。
clifd = socket(AF_INET,SOCK_STREAM,0);
if(-1 == clifd)
{
perror("socket");
return -1;
}
struct sockaddr_in servaddr;
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(7777);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
socklen_t len = sizeof(servaddr);
ret = connect(clifd,(struct sockaddr *)&servaddr,len);
if(-1 == ret)
{
perror("connext");
return -1;
}
pfd[0].fd = 0;
pfd[1].fd = clifd;
pfd[0].events = pfd[1].events = POLLIN;
while(1)
{
ret = poll(pfd,2,-1);
if(ret > 0)
{
if(pfd[0].revents == POLLIN)
{
//读终端
memset(buf,0,sizeof(buf));
ret = read(pfd[0].fd,buf,sizeof(buf)-1);
if(ret > 0)
{
buf[ret] = '\0';
write(clifd,buf,ret);
}
}
if(pfd[1].revents == POLLIN)
{
//读套接字
memset(buf,0,sizeof(buf));
ret = read(pfd[1].fd,buf,sizeof(buf)-1);
if(ret > 0)
{
buf[ret] = '\0';
printf("server say:%s\n",buf);
}
}
}
else if(ret == 0)
{
printf("超时。。。。\n");
return -1;
}
else
{
perror("poll");
return -1;
}
}
close(clifd);
return 0;
}