/******* 服务器程序(server.c) ************/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
//#include <pthread.h>
typedef unsigned long int pthread_t;
#define MAXLINE 1000//在一条消息中最大的输出字符数
#define LISTENQ 20//最大监听队列
#define PORT 5000//监听端口
#define MAXFD 20//最大的在线用户数量
void *get_client(void *);
int sockfd,i;
static int maxi=0;//maxi表示当前client数组中最大的用户的i值
static int client[MAXFD];
void recvandsend(void)//监听转发线程入口函数
{
int index=0;
int nbytes=0;
char buffer[1024];
int len;
int outindex=0;
while(1)
{
if(maxi>0)
{
memset(buffer,0,sizeof(buffer));
nbytes=0;
//index++;
nbytes=read(client[index++],buffer,sizeof(buffer));
// printf("%d,%d\n",index,client[index]);
if(nbytes>0)
{
buffer[nbytes]='\0';
printf("%s\n",buffer);
outindex=0;
while(outindex<maxi)
{
if(write(client[outindex++],buffer,sizeof(buffer))==-1)
{
fprintf(stderr,"WriteError:%s\n",strerror(errno));
exit(1);
}
}
}
}
if(index>=maxi)
index=0;
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
// int client_fd[LISTENQ],clientnum=0;;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int sin_size,portnumber;
char hello[]="Hello! Are You Fine?\n";
int thr_id; /* thread ID for the newly createdthread */
pthread_t p_thread; /* thread's struct ure */
int new_fd=0;
memset(client,0,sizeof(client));
if(argc!=1)
{
fprintf(stderr,"Usage:%sportnumber\a\n",argv[0]);
exit(1);
}
/* 服务器端开始建立 socket 描述符 */
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
fprintf(stderr,"Socketerror:%s\n\a",strerror(errno));
exit(1);
}
/* 服务器端填充 sockaddr 结构 */
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
server_addr.sin_port=htons(PORT);
/* 捆绑 sockfd 描述符 */
if(bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)
{
fprintf(stderr,"Binderror:%s\n\a",strerror(errno));
exit(1);
}
printf("服务器监听端口%d...\n",PORT);
/* 监听 sockfd 描述符 */
if(listen(sockfd,LISTENQ)==-1)
{
fprintf(stderr,"Listenerror:%s\n\a",strerror(errno));
exit(1);
}
thr_id =pthread_create(&p_thread, NULL, recvandsend, NULL);
printf("欢迎来到本聊天室\n");
while(1)
{
/* 服务器阻塞,直到客户程序建立连接 */
if(maxi>=20)
{
printf("以达到人数上线\n");
continue;
}
sin_size=sizeof(struct sockaddr_in);
if((new_fd=accept(sockfd,(struct sockaddr *)(&client_addr),&sin_size))==-1)
{
fprintf(stderr,"Accepterror:%s\n\a",strerror(errno));
exit(1);
}
/*fprintf(stderr,"Serverget connection from %s\n",inet_ntoa(client_addr.sin_addr));*/
client[maxi++]=new_fd;
printf("\n新用户进入聊天室%d\n",new_fd);
}
close(sockfd);
exit(0);
}
评论0
最新资源