Linux C语言网络编程epoll多客户端,服务器转发

下面是server代码:

服务器主要负责等待客服端连接,处理数据,转发!随便瞎写的,主要是为了学习epoll多路复用,有逻辑错误的地方。

#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <netinet/in.h>
#include <errno.h>
#include <sys/epoll.h>
#include <semaphore.h>

#define  OPEN_MAX 20


typedef struct {
	int client_fd;
	char client_name[128];
	struct sockaddr_in client_addr;

}client;
static client *clients = NULL;
static sem_t send_sem;
char from[32] = {0};
char to[32] = {0};
char msg[128] = {0};
char recv_buf[1024] = {0};
struct epoll_event event; 
struct epoll_event wait_event;
int server_fd = -1,target_fd = -1,epfd = -1;
static int retVal = -1;
static int sin_size = 0;
struct sockaddr_in server_addr;
struct sockaddr_in new_client_addr;
pthread_t send_thread_id;
pthread_t recv_thread_id;

/*
 *
 *
 * test 
 *
 *
 * */

static void showAllClients(void)
{
	int i;
	for(i = 0; i < OPEN_MAX; i++){
		if(clients[i].client_fd == 0){
			continue;
		}else{
			printf("showAllClients clients[%d]:client_fd = %d :name = %s\n",i,clients[i].client_fd,clients[i].client_name);
		}
	}
}

static int getClientsIndex(int byfd, char * byname)
{
	int i;
	if( byfd > 0 ){
		for(i = 0; i < OPEN_MAX;i++){
			if(clients[i].client_fd == byfd){
				return i;
			}else{
				continue;
			}
		}
	}
	else if ( byname != NULL){
		for(i = 0; i < OPEN_MAX;i++){
			if(strstr(clients[i].client_name,byname)){
				return i;
			}else{
				continue;
			}
		}
	}
	else {
		printf("getClientsIndex error\n");
		return -1;
	}

}

void send_thread(void)
{
	int i = 0;
	while(1){
		sem_wait(&send_sem);
		int index = getClientsIndex(0,to);
		if(index < 0){
			continue;
		}
		printf("index =%d,target_fd =%d\n",i
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值