下面是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