⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.c

📁 Linux下服务器即时通信程序
💻 C
字号:
#include <arpa/inet.h>#include<stdlib.h>#include<unistd.h>#include<errno.h>#include<sys/socket.h>#include<sys/select.h>#include <sys/types.h>#include <sys/stat.h>#include<stdio.h>#define MAX_LISTEN 10char *buff2;//接受客户数据int recv_data(int sock, char *buf, int len){	int lt=0;	if((lt=read(sock, buf,len)) < 0){		perror("recv error");		return -1;	  }	else if(lt == 0){		printf("client shutdown the socket %d", sock);		return 0;	  }    printf("recv data %s\n", buf);	return lt;}//将数据发到客户指定地点int send_data(char *buf){	int i=0;	while((*(buff2+i) = *(buf + i + 1)) != '\0')		i++;}	intmain(void){	int client,ret,i,max_fd;	char sig;	char buff[1000]; //客户数据缓存	char buf2[10]={0,1,2,3,4,5,6,7,8,9};  //10个客户 	int sock;	struct sockaddr_in addr;	int client_fd[MAX_LISTEN];    	fd_set readset,writeset;	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)	{		perror("socket");		exit(1);	}	addr.sin_family = AF_INET;	addr.sin_port = htons(2008);	inet_pton(AF_INET, "192.168.1.57", &addr.sin_addr);	if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0){        perror("bind");        exit(1);       }		listen(sock, MAX_LISTEN);  	   	for(i = 0;i < MAX_LISTEN;i++)      client_fd[i]= -1;	FD_ZERO(&writeset);    max_fd=sock;while(1){        FD_ZERO(&readset);	FD_CLR(sock,&readset);	FD_CLR(sock,&writeset);    FD_SET(sock,&readset);	FD_SET(sock,&writeset);   if((ret= select(max_fd+1 , &readset , &writeset , NULL , NULL)) < 0)   {	   perror("select");	   exit(-1);   }   else if( ret == 0)   {  	   printf("select timeout\n");       continue;   }   printf("select\n ");     if( FD_ISSET(sock, &readset)){	   if( (client = accept(sock, NULL, NULL) < 0))	   {		    perror("accept failed");			continue;	   }	   for(i=0;i<MAX_LISTEN;i++)	   {		   if(client_fd[i] != -1)			   continue;		   client_fd[i] = client;		   FD_SET(client,&readset);		    break;	   }	   if(max_fd < client)		   max_fd = client;	   printf("add client socket connection %d \n", i);	   continue;   }     FD_SET(client, &writeset);  for(i=0;i < MAX_LISTEN;i++){	  if( client_fd[i] ==-1)		  continue;	  if(!FD_ISSET( client_fd[i],&readset))		  continue;     if( (ret = recv_data(client_fd[i], buff, sizeof(buff))) <= 0)             {	    close(client_fd[i]);		FD_CLR( client_fd[i], &readset);		printf("del socket %d from select pipe.\n",client_fd[i]);		client_fd[i] = -1;		}     else       printf("%s\n",buff);		 	   send_data(buff);      sig=*buff;  if( FD_ISSET(client_fd[sig], &writeset)){	if ( (ret =send(client_fd[sig], buff2, sizeof(buff2), MSG_EOR)) < 0){		perror(" send error");		return -1;	   }    else	printf("send %d data\n", sizeof(buff2));  }   }      max_fd = sock;    for(i = 0; i < MAX_LISTEN;i++){	if(max_fd < client_fd[i])	 max_fd = client_fd[i];   }  }return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -