Chinaunix首页 | 论坛 | 博客
  • 博客访问: 87920
  • 博文数量: 16
  • 博客积分: 86
  • 博客等级: 民兵
  • 技术积分: 222
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-08 17:46
文章分类

全部博文(16)

文章存档

2014年(1)

2013年(15)

分类: LINUX

2013-03-08 02:33:16

server.c

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


#include
#include
#include
#define PORT 1234
void handle(void* p)
{
printf("create a pthread\n");
int clientfd = *(int*)p;
char buf[100];
char display[200];
char name[10];
char sendstring[] = "please input your name";
int re;
send(clientfd, sendstring, strlen(sendstring), 0);
bzero(name, 10);
re = recv(clientfd, name, 10, 0);
name[re-1] = '\0';
printf("connected by %s\n", name);

while(1)
{


bzero(buf, 100);
if((re = recv(clientfd, buf, 100, 0)) < 0)
{
perror("recv");
exit(1);
}
else if(re == 0)
{
break;
}
bzero(display, 200);
strcat(display, name);
strcat(display, " : ");
strcat(display, buf);
printf("%s",display);
if(strncmp(buf, "1", 1) ==0)
{
send(clientfd, "command is 1", 12, 0);
}
else if(strncmp(buf, "2", 1) ==0)
{
send(clientfd, "command is 2", 12, 0);
}
else if(strncmp(buf, "3", 1) ==0)
{
send(clientfd, "command is 3", 12, 0);
}
}
close(clientfd);
}




int main(void)
{
pthread_t tid;
int sockfd, clientfd, size;
struct sockaddr_in serveraddr, clientaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0 );
if(sockfd == -1)
{
perror("socket");
exit(1);
}
bzero(&serveraddr, sizeof(struct sockaddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = INADDR_ANY;
serveraddr.sin_port = htons(PORT);
int i = 1 ;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
if(bind(sockfd, (struct sockaddr*)&serveraddr,sizeof(struct sockaddr)) < 0)
{
perror("bind");
exit(1);
}
if(listen(sockfd, 10) < 0)
{
perror("listen");
exit(1);
}
while(1)
{
size = sizeof(struct sockaddr);
clientfd = accept(sockfd, (struct sockaddr*)&clientaddr, &size);
if(clientfd ==  -1)
{
perror("accept");
exit(1);
}
pthread_create(&tid, NULL, (void*)handle, &clientfd);
}


close(sockfd);
return 0;

}



client.c



阅读(1148) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~