一个不完善的多线程服务器模型

根据:http://www.kumouse.com/article.asp?id=141
中的服务端改写而成,刚学不久,只是练练手的。有高人路过,还请指点
字符串长度n没有当参数传递,所以会是0,退出要第二次发数据才行,其实用消息处理函数,CTRL+C就可能搞定了
[ssj@main test]$ cat rs_easyserver.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>
#define MAX 200
#define BB 16
int k=0;
void my_turn(char *p)
{sleep(10);
if (p == NULL)return;
while( *p != '')
{
if( *p >= (char)0x61 && *p <= (char)0x7a)
*p=(char)((int)*p-(int)0x20);
p++;
}
}

typedef struct arg_struct ARG;
struct arg_struct{
int cfd;
};
void *f1(void *arg)
{
char buf[MAX];
char addr_p[BB];
int n,cfd;
ARG *p=(ARG *)arg;
cfd=p->cfd;
n=recv(cfd,buf,MAX,0);
if (n==-1)
{
perror("Fail to recv");
exit(1);
}
else if(n==0)
{
printf("the connect closedn");
close(cfd);
exit(1);
}
if (strcmp(buf,"close")==0){k=1;}
printf("type:%sn",buf);
my_turn(buf);
printf("turn type:%sn=================================n",buf);
n=send(cfd,buf,n,0);
if(n==-1){
perror("Fail to send");
exit(1);
}
if(close(cfd)==-1)
{
perror("Fail to close");
exit(1);
}

}

int main(void)
{
struct sockaddr_in sin,cin;
struct sockaddr *tmp;
int lfd,cfd;
socklen_t len;
char buf[MAX];
char addr_p[BB];
int n,err,port = 65533;
pthread_t tid;
ARG arg;
bzero(&sin,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_addr.s_addr=INADDR_ANY;
sin.sin_port=htons(port);

if((lfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("Fail to create socket");
exit(1);
}

if(bind(lfd,(struct sockaddr *)&sin,sizeof(sin))==-1)
{
perror("Fail to bind");
exit(1);
}
if(listen(lfd,10)==-1)
{
perror("Fail to listen");
exit(1);
}
printf("running……….n");

while(1)
{
if((cfd=accept(lfd,(struct sockaddr *)&cin,&len))==-1)
{
perror("Fail to accept");
exit(1);
}else{
inet_ntop(AF_INET,&cin.sin_addr,addr_p,sizeof(addr_p));
// printf("client IP is:%s:%d size:%dn",addr_p,ntohs(cin.sin_port),n);
arg.cfd=cfd;
err=pthread_create(&tid,NULL,f1,(void *)&arg);
if (err!=0){printf("%sn",strerror(err));exit(1);}
}
printf("client IP is:%s:%d Pthread:%d size:%dn",addr_p,ntohs(cin.sin_port),tid,n);
if (k==1)
{close(cfd);close(lfd);exit(0);}
}

if(close(cfd)==-1)
{
perror("Fail to close");
exit(1);
}

if(close(lfd)==-1)
{
perror("fail close");
exit(1);
}
return 0;
}

注:编译时加-lpthread参数,pthread_create不在默认库里

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注