前言
本文承接上一篇《Linux多人聊天室之前篇》的内容,记录的是多人聊天室室如何实现的。
一、前期工作
前期工作包含有:①学会用内核链表。②知道多线程的原理。
内核链表:
学习存储客户端的已连接套接字的数据结构 – 内核链表。
1、为什么项目中不使用数组,而是使用链表?
因为数组必须要在定义时,确定出数组的空间大小,那么这样就会限制了客户端连接的人数。
例如:int connfd[10]; --> 最多只能有10个客户端连接
2、链表是什么东西来的?
链表是linux下的一种存储结构。
3、如何实现内核链表的初始化头节点、尾插、遍历、删除节点?
1)内核链表所有的操作函数都已经帮你实现好了,你只需要调用即可。
这些操作函数都是放在kernel_list.h,所以待会编译代码,这个头文件必须存放才会编译通过。
2)如何表示一个节点?
经过分析,一个节点既有数据域,又有指针域,最好使用一个结构体来表示?
struct list_node{
//数据域
int connfd; --> 代表每一个节点都是存放一个已连接套接字
//指针域
struct list_head list;
};
指针域在内核链表已经写好了,指针域是一个结构体的:
struct list_head {
struct list_head *next, *prev; //分别是指向下一个节点与上一个节点
};
3)如何申请空间?
使用malloc()函数
头文件:#include <stdlib.h>
malloc() 参数: 你想申请的空间大小的字节数
malloc() 返回值: 这片新申请的空间的地址
4)如何初始化头节点?
INIT_LIST_HEAD(节点结构体指针域的地址)
5)如何尾插?
list_add_tail(新节点结构体指针域的地址,头节点结构体指针域的地址)
6)如何遍历?
list_for_each_entry(指向节点结构体的指针p变量,头节点结构体指针域的地址,在节点结构体中,指针域变量叫什么名字)
7)如何删除?
list_for_each_entry_safe(指向节点结构体的指针p变量,指向节点结构体的指针q变量,头节点结构体指针域的地址,在节点结构体中,指针域变量叫什么名字)
8)如何把这个节点从链表中脱离?
list_del(那个需要脱离的节点的指针域的地址)
9)如何释放节点空间?
使用free()函数
详细的代码: list_test.c

list_test.c代码:
#include <stdio.h>
#include "kernel_list.h" //包含当前目录下的kernel_list.h
#include <stdlib.h>
//设计节点
struct list_node{
int connfd;
struct list_head list; //这个结构体不需要我们自己写,
//因为这个结构体已经在kernel_list.h中已经定义好了。
};
struct list_node *init_list_head()
{
//1. 为头节点申请空间
struct list_node *head = malloc(sizeof(struct list_node));
//2. 为头节点赋值
INIT_LIST_HEAD(&(head->list));
//3. 将头节点返回给main函数,以便后续的尾插、遍历,删除使用。
return head;
}
void insert_list_node(struct list_node *head,int num)
{
//1. 为新节点申请空间
struct list_node *New_Node = malloc(sizeof(struct list_node));
//2. 为数据域赋值
New_Node->connfd = num;
//3. 为指针域赋值
list_add_tail(&(New_Node->list),&(head->list));
return;
}
void show_list_node(struct list_node *head)
{
struct list_node *p = NULL;
list_for_each_entry(p, &(head->list), list)
{
printf("p->connfd:%d\n",p->connfd);
}
return;
}
void delete_list_node(struct list_node *head,int num)
{
struct list_node *p = NULL;
struct list_node *q = NULL;
list_for_each_entry_safe(p,q,&(head->list),list)
{
//每遍历到一个节点,我都判断一下是不是我想删除的节点
if(p->connfd == num) //找到了我想删除的节点
{
list_del(&(p->list)); //让该节点从链表中脱离
free(p); //释放p节点指向的空间
return;
}
}
}
int main(int argc,char *argv[])
{
//1. 初始化头节点
struct list_node *head = NULL;
head = init_list_head();
//2. 尾插(当有客户端连接到服务器,就要使用到尾插的函数)
insert_list_node(head,4);
insert_list_node(head,5);
insert_list_node(head,6);
insert_list_node(head,7);
insert_list_node(head,8);
//3. 遍历(如果需要群发或者私聊,就要使用到遍历)
show_list_node(head); //45678
//4. 删除节点
delete_list_node(head,6); //(当客户端发送额quit要退出时,就要删除该客户端节点)
//5. 再次遍历链表
printf("------------------------\n");
show_list_node(head); //4578
return 0;
}
多线程:由于本人博客已经有记录过多线程的内容,本文不再重复
二、项目框架

三、伪代码流程

四、源代码
服务端代码如下(示例):
/************************************************************************
*
* 文件名:server.c
*
* 功能:服务端(一般用于接收数据)
*
* 创建人:LZH
*
* 时间:2021年11月14日20:13:47
*
* 版本号:1.0
*
* 修改记录:无
*
************************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include "kernel_list.h" //包含当前目录下的kernel_list.h
//设计节点
typedef struct list_node{
int connfd;
struct list_head list; //这个结构体不需要我们自己写,
//因为这个结构体已经在kernel_list.h中已经定义好了。
}NODE, *PNODE;
struct list_node *init_list_head(); //链表初始化
void insert_list_node(struct list_node *head,int num);
void show_list_node(struct list_node *head);
void delete_list_node(struct list_node *head,int num);
void* func(void* arg);
//初始化存储已连接套接字的链表 add by LZH
PNODE head = NULL;
int main(int argc, char const *argv[]) {
//1、准备一个未连接的套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
head = init_list_head();
//2、绑定一个IP地址到套接字上
struct sockaddr_in seraddr;
socklen_t len = sizeof(seraddr);
bzero(&seraddr, len); //赋值前先清空seraddr内存上数据
seraddr.sin_family = AF_INET; //设置服务器协议
seraddr.sin_port = htons(atoi(argv[1])); //设置服务器的端口号(把字符串转成短整型)
seraddr.sin_addr.s_addr = htonl(INADDR_ANY); //设置服务器的IP地址
bind(sockfd, (struct sockaddr *)(&seraddr), len);
//3、将未连接套接字转换成监听套接字
listen(sockfd, 5);
//4、不断等待监听套接字上的数据
struct sockaddr_in cliaddr;
bzero(&cliaddr, len);
int connfd;
while(1) {
connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &len); //谁连接到服务器上,谁的信息就会保存到这个变量中。
//insert_list_node(head,4);
if(connfd > 0) {
insert_list_node(head, connfd); //尾插,把connfd添加链表当中
printf("new connection:%d\n", connfd); //OK
//show_list_node(head); //遍历链表,查看是否添加成功
pthread_t pid;
pthread_create(&pid, NULL, func, (void*)&connfd);
} else {
printf("accept function error!\n");
}
}
//6. 挂断
//close(connfd);
close(sockfd);
return 0;
}
//线程回调函数
void* func(void* arg) {
//5. 畅聊 不断接受客户端发送过来的数据
char buf[100];
int connfd = *(int*)arg;
while(1) {
//5.1 清空缓冲区
bzero(buf, sizeof(buf));
//5.2 把已连接套接字上的数据读取到缓冲区
recv(connfd, buf, sizeof(buf), 0);
//5.3 将缓冲区的数据打印出来
//printf("from connfd:%d client: %s", connfd, buf);
//5.4 如果客户端给我发了quit,那么我就退出
if( strncmp(buf, "quit", 4) == 0 )
{
close(connfd);
delete_list_node(head, connfd); //(当客户端发送额quit要退出时,就要删除该客户端节点)
//free(&connfd);
}
//判断buf中有没有 冒号:
char* tmp = strstr(buf, ":");
if(tmp == NULL) {
//群发
struct list_node *p = NULL;
list_for_each_entry(p, &(head->list), list)
{
if(p->connfd != connfd) {
send(p->connfd, buf, strlen(buf), 0); //群发信息给每个客户端
}
//printf("p->connfd:%d\n", p->connfd);
}
} else {
//如果buf的第二个信息不是“冒号:”,那么将它认为是群发信息
if(buf[1] != ':') {
//群发
struct list_node *p = NULL;
list_for_each_entry(p, &(head->list), list)
{
if(p->connfd != connfd) {
send(p->connfd, buf, strlen(buf), 0); //群发信息给每个客户端
}
//printf("p->connfd:%d\n", p->connfd);
}
} else {
//私聊
char* str = tmp + 1; //私聊内容
int num = atoi(buf); //找到对方的ID号 (5:hello),找到这个5
send(num, str, strlen(str), 0); //群发信息给每个客户端
}
}
}
}
//链表初始化
struct list_node *init_list_head() {
//1. 为头节点申请空间
struct list_node *head = malloc(sizeof(struct list_node));
//2. 为头节点赋值
INIT_LIST_HEAD(&(head->list));
//3. 将头节点返回给main函数,以便后续的尾插、遍历,删除使用。
return head;
}
//尾插法
void insert_list_node(struct list_node *head,int num)
{
//1. 为新节点申请空间
struct list_node *New_Node = malloc(sizeof(struct list_node));
//2. 为数据域赋值
New_Node->connfd = num;
//3. 为指针域赋值
list_add_tail(&(New_Node->list),&(head->list));
return;
}
//遍历链表
void show_list_node(struct list_node *head)
{
struct list_node *p = NULL;
list_for_each_entry(p,&(head->list),list)
{
printf("p->connfd:%d\n",p->connfd);
}
return;
}
//删除结点
void delete_list_node(struct list_node *head,int num)
{
struct list_node *p = NULL;
struct list_node *q = NULL;
list_for_each_entry_safe(p,q,&(head->list),list)
{
//每遍历到一个节点,我都判断一下是不是我想删除的节点
if(p->connfd == num) //找到了我想删除的节点
{
list_del(&(p->list)); //让该节点从链表中脱离
free(p); //释放p节点指向的空间
return;
}
}
}
客户端代码如下(示例):
/************************************************************************
*
* 文件名:client.c
*
* 功能:客户端
*
* 创建人:LZH
*
* 时间:2021年11月14日00:29:46
*
* 版本号:1.0
*
* 修改记录:无
*
************************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
void* func(void* arg);
int main(int argc, char const *argv[])
{
//1、准备一个未连接的套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
//2. 准备服务器的地址
struct sockaddr_in seraddr;
socklen_t len = sizeof(seraddr);
bzero(&seraddr, len); //赋值前先清空seraddr内存上数据
seraddr.sin_family = AF_INET; //设置服务器协议
seraddr.sin_port = htons(atoi(argv[2])); //设置服务器的端口号(把字符串转成短整型)
inet_pton(AF_INET, argv[1], &seraddr.sin_addr); //设置服务器IP地址
//3. 直接发起连接
int ret = connect(sockfd, (struct sockaddr *)(&seraddr), len);
if(ret == 0) {
printf("connect success!\n");
} else {
printf("connect fail!\n");
}
pthread_t pid;
pthread_create(&pid, NULL, func, (void*)&sockfd );
//4. 不断发送数据给服务器。
char buf[100];
while(1)
{
//4.1 先清空缓冲区
bzero(buf, sizeof(buf));
//4.2 从键盘中获取字符串,然后把字符串存储到这个数组中。
fgets(buf, sizeof(buf), stdin); //stdin就是键盘设备对应的文件指针
//4.3 发送该字符串给服务器
send(sockfd, buf, strlen(buf), 0); //strlen(buf)可以计算出字符串实际的字符个数
//4.4 判断发送的字符串是不是quit
if( strncmp(buf, "quit", 4) == 0 )
{
break; //如果收到了quit,则跳出循环,程序结束
}
}
//5. 挂断电话
close(sockfd);
return 0;
}
void* func(void* arg) {
int sockfd = *(int*)arg;
char buf[100];
while(1) {
bzero(buf, sizeof(buf));
recv(sockfd, buf, sizeof(buf), 0);
printf("receive from other:%s\n", buf);
}
}
五、结果显示

附录
此项目还需要一个内核链表的头文件
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 [squiggly] 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
本文详细介绍了如何使用Linux内核链表数据结构和多线程技术实现一个多人聊天室。首先讲解了内核链表的用途,避免数组限制连接数,并展示了链表的初始化、插入、遍历和删除操作。接着,文章概述了项目的框架,给出了服务端和客户端的伪代码流程及源代码。服务端通过监听套接字接收客户端连接,将连接套接字信息存储在链表中,使用线程处理每个客户端的通信,实现群发和私聊功能。客户端则负责连接服务端并发送数据,接收到'quit'时断开连接。附录中提供了内核链表头文件`kernel_list.h`的代码。
1938

被折叠的 条评论
为什么被折叠?



