jun 发表于 2016-5-3 17:06:35

服务器转发客户端发来的信息(多线程实现--利用内核链表)

--------------------------head.h------------------------------------
#ifndef _HEAD_MULTITHREAD_H_
#define _HEAD_MULTITHREAD_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <pthread.h>

#define SIZE 100

#endif

---------------------------------------------------------------
-------------------------kernel_list.h-------------------------
#ifndef __DLIST_H
#define __DLIST_H

/* This file is from Linux Kernel (include/linux/list.h)
* and modified by simply removing hardware prefetching of list items.
* Here by copyright, credits attributed to wherever they belong.
* Kulesh Shanmugasundaram (kulesh isis.poly.edu)
*/

/*
* Simple doubly linked list implementation.
*
* Some of the internal functions (“__xxx”) are useful when
* manipulating whole lists rather than single entries, as
* sometimes we already know the next/prev entries and we can
* generate better code by using them directly rather than
* using the generic single-entry routines.
*/
/**
* container_of - cast a member of a structure out to the containing structure
*
* @ptr:        the pointer to the member.
* @type:        the type of the container struct this is embedded in.
* @member:        the name of the member within the struct.
*
*/
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

#define container_of(ptr, type, member) ({                        \
      const typeof( ((type *)0)->member ) *__mptr = (ptr);        \
      (type *)( (char *)__mptr - offsetof(type,member) );})
/*
* These are non-NULL pointers that will result in page faults
* under normal circumstances, used to verify that nobody uses
* non-initialized list entries.
*/
#define LIST_POISON1((void *) 0x00100100)
#define LIST_POISON2((void *) 0x00200)

struct list_head {
        struct list_head *next, *prev;
};


#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)


#define INIT_LIST_HEAD(ptr) do { \
        (ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)




/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *new,
                                struct list_head *prev,
                                struct list_head *next)
{
        next->prev = new;
        new->next = next;
        new->prev = prev;
        prev->next = new;
}

/**
* list_add – add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *new, struct list_head *head)
{
        __list_add(new, head, head->next);
}

/**
* list_add_tail – add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
        __list_add(new, head->prev, head);
}

/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
        next->prev = prev;
        prev->next = next;
}

/**
* list_del – deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty on entry does not return true after this, the entry is in an undefined state.
*/
static inline void list_del(struct list_head *entry)
{
        __list_del(entry->prev, entry->next);
        entry->next = (void *) 0;
        entry->prev = (void *) 0;
}

/**
* list_del_init – deletes entry from list and reinitialize it.
* @entry: the element to delete from the list.
*/
static inline void list_del_init(struct list_head *entry)
{
        __list_del(entry->prev, entry->next);
        INIT_LIST_HEAD(entry);
}

/**
* list_move – delete from one list and add as another’s head
* @list: the entry to move
* @head: the head that will precede our entry
*/
static inline void list_move(struct list_head *list,
                                struct list_head *head)
{
        __list_del(list->prev, list->next);
        list_add(list, head);
}





/**
* list_move_tail – delete from one list and add as another’s tail
* @list: the entry to move
* @head: the head that will follow our entry
*/
static inline void list_move_tail(struct list_head *list,
                                        struct list_head *head)
{
        __list_del(list->prev, list->next);
        list_add_tail(list, head);
}

/**
* list_empty – tests whether a list is empty
* @head: the list to test.
*/
static inline int list_empty(struct list_head *head)
{
        return head->next == head;
}

static inline void __list_splice(struct list_head *list,
                                        struct list_head *head)
{
        struct list_head *first = list->next;
        struct list_head *last = list->prev;
        struct list_head *at = head->next;

        first->prev = head;
        head->next = first;

        last->next = at;
        at->prev = last;
}

/**
* list_splice – join two lists
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static inline void list_splice(struct list_head *list, struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head);
}

/**
* list_splice_init – join two lists and reinitialise the emptied list.
* @list: the new list to add.
* @head: the place to add it in the first list.
*
* The list at @list is reinitialised
*/
static inline void list_splice_init(struct list_head *list,
struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head);
INIT_LIST_HEAD(list);
}
}



/**
* list_entry – get the struct for this entry
* @ptr:    the &struct list_head pointer.
* @type:    the type of the struct this is embedded in.
* @member:    the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

/**
* list_for_each    -    iterate over a list
* @pos:    the &struct list_head to use as a loop counter.
* @head:    the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); \
pos = pos->next)
/**
* list_for_each_prev    -    iterate over a list backwards
* @pos:    the &struct list_head to use as a loop counter.
* @head:    the head for your list.
*/
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev; pos != (head); \
pos = pos->prev)

/**
* list_for_each_safe    -    iterate over a list safe against removal of list entry
* @pos:    the &struct list_head to use as a loop counter.
* @n:      another &struct list_head to use as temporary storage
* @head:    the head for your list.
*/
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)

/**
* list_for_each_entry    -    iterate over list of given type
* @pos:    the type * to use as a loop counter.
* @head:    the head for your list.
* @member:    the name of the list_struct within the struct.
*/
#define list_for_each_entry(pos, head, member)                \
for (pos = list_entry((head)->next, typeof(*pos), member);    \
&pos->member != (head);                     \
pos = list_entry(pos->member.next, typeof(*pos), member))

/**
* list_for_each_entry_safe – iterate over list of given type safe against removal of list entry
* @pos:    the type * to use as a loop counter.
* @n:      another type * to use as temporary storage
* @head:    the head for your list.
* @member:    the name of the list_struct within the struct.
*/
#define list_for_each_entry_safe(pos, n, head, member)            \
for (pos = list_entry((head)->next, typeof(*pos), member),    \
n = list_entry(pos->member.next, typeof(*pos), member);    \
&pos->member != (head);                     \
pos = n, n = list_entry(n->member.next, typeof(*n), member))

#endif

----------------------------------------------------------------------


-----------------------客户端-----------------------------------------
#include "head.h"
#include "kernel_list.h"

#define handle_error(msg) \
      do { perror(msg); exit(EXIT_FAILURE); } while (0)

void *routine(void *arg)
{
      int fd = (int)arg;
      char buf;
      while(1){
                bzero(buf, SIZE);
                if(0 == read(fd, buf, SIZE))
                        break;
                printf("From server: %s", buf);
      }
}

int main(int argc, char **argv)
{
      char buf;
      int fd;
      struct sockaddr_in server_addr;
      if(3 != argc){
                printf("Usage:%s <IP> <PORT>\n", argv);
                return -1;
      }
      bzero(&server_addr, sizeof(server_addr));

      fd = socket(AF_INET, SOCK_STREAM, 0);
      if(fd == -1)
                handle_error("socket");

      //memset(&server_addr, 0, sizeof(struct sockaddr_in));
      server_addr.sin_family = AF_INET;
      server_addr.sin_port = htons(atoi(argv));
      //server_addr.sin_addr.s_addr = inet_pton("192.168.1.77");
      inet_pton(AF_INET, argv, &server_addr.sin_addr);
      
      // connet server
      if(connect(fd, (struct sockaddr *) &(server_addr),
                sizeof(server_addr)) == -1)
                handle_error("connect");
      // create a thread for reading data
      pthread_t tid;
      pthread_create(&tid, NULL, routine, (void *)fd);

      // write data
      while(1){
                bzero(buf, SIZE);
                printf("Enter please:\n");
                fgets(buf, SIZE, stdin);
                send(fd, (void *)buf, SIZE, MSG_DONTWAIT);
                if(!strcmp(buf, "quit\n"))
                        break;
      }
      close(fd);
      return 0;
}
------------------------------------------------------------------------

--------------------服务器端-----------------------------------------
#include "head.h"
#include "kernel_list.h"

#define handle_error(msg) \
        do { perror(msg); exit(EXIT_FAILURE); } while (0)

typedef struct{
        int fd;
        struct list_head list;
}client;

client *head;

void broad_cast(const char *msg, int sender)
{
        struct list_head *pos;
        // Traversing the entire customer list
        list_for_each(pos, &head->list){
                client *tmp = list_entry(pos, client, list);
                // Skip itself
                if(tmp->fd == sender)
                        continue;
                // Send msg to other
                write(tmp->fd, msg, strlen(msg));
        }

}

void del_client(int quitor)
{
        struct list_head *pos, *n;
        // It is a 'for' loop traverse the list
        list_for_each_safe(pos, n, &head->list){
                client *tmp = list_entry(pos, client, list);
                if(tmp->fd == quitor){
                        list_del(pos);
                        free(tmp);
                        break;
                }
        }
}

void *routine(void *arg)
{
        // Get TID of itself and detach itself,make sure it
        // can free source when it quit
        pthread_detach(pthread_self());
        int fd = (int)arg;
        char buf;
        while(1){
                bzero(buf, SIZE);
                if(read(fd, buf, SIZE) == 0 || !strcmp(buf, "quit\n")){
                        del_client(fd);
                        break;
                }
                broad_cast(buf, fd);
        }
        pthread_exit(NULL);
}

client *init_list(void)
{
        head = malloc(sizeof(client));
        if(head != NULL)
                INIT_LIST_HEAD(&head->list);       
        return head;
}

client *new_cli(int fd)
{
        client *new = malloc(sizeof(client));
        if(new != NULL){
                new->fd = fd;
                INIT_LIST_HEAD(&new->list);
        }
        return new;
}

int main(int argc, char **argv)
{
        char buf;
        int fd_s, fd_c;
        socklen_t len;
        struct sockaddr_in srvaddr, cliaddr;
        if(2 != argc){
                printf("Usage:%s <PORT>\n", argv);
                return -1;
        }
        fd_s = socket(AF_INET, SOCK_STREAM, 0);
        if(fd_s == -1)
                handle_error("socket");

        /* clear structure */
        memset(&srvaddr, 0, sizeof(struct sockaddr_in));
        srvaddr.sin_family = AF_INET;
        srvaddr.sin_port = htons(atoi(argv));
        inet_pton(AF_INET, "0.0.0.0", &srvaddr.sin_addr);
        // OR srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        // #define INADDR_ANY (u_intSIZE_t) 0x00000000

        if(bind(fd_s, (struct sockaddr *) &srvaddr,
                sizeof(struct sockaddr)) == -1)
                handle_error("bind");

        if(listen(fd_s, 3) == -1)
                handle_error("listen");
       
        head = init_list();

        len = sizeof(struct sockaddr);
        while(1){
                fd_c = accept(fd_s, (struct sockaddr *) &cliaddr, &len);
                if(fd_c == -1)
                        handle_error("accept");
               
                char cli_buf;
                bzero(cli_buf, 50);
                printf("new connection:%s:%hu\n",
                        (char *)inet_ntop(AF_INET, &cliaddr.sin_addr, cli_buf, 50),
                        ntohs(cliaddr.sin_port));
               
                // Create a new client node and put it into the end of list
                client *new = new_cli(fd_c);
                list_add_tail(&new->list, &head->list);

                pthread_t tid;
                pthread_create(&tid, NULL, routine, (void *)fd_c);
        }
        close(fd_s);
        return 0;
}

------------------------------------------------------------------------------------
-------------------------Usage------------------------------
gcc -o client client.c -lpthread
gcc -o server server.c -lpthread
--------------------------------
一个server端
两个或两个以上client端
才能确保你能看到效果
--------------------------------
./server50001
./client 127.0.0.150001 打开第一个客户端
./client 127.0.0.150001 打开第二个客户端(用另一个终端打开)

-------------------------------------------------------------------------


ELI_ 发表于 2016-6-30 22:40:08

谢谢分享

jun 发表于 2016-7-1 19:53:32

ELI_ 发表于 2016-6-30 22:40
谢谢分享

没想到LINUX论坛居然有人回少见啊

ELI_ 发表于 2016-7-1 21:23:33

新鱼友表示就是要顶你的帖
页: [1]
查看完整版本: 服务器转发客户端发来的信息(多线程实现--利用内核链表)