我正在尝试用 C 语言制作一个简单的聊天服务(套接字编程)。
服务器是并发的,可以接受多个连接。我使用服务器线程和链表来保存套接字 ID。除了我用于从链表中删除节点的删除功能外,一切正常。每当客户端键入 DONE
时,我都必须从链表中删除它的套接字 ID,但它无法正常工作。有人可以帮我弄清楚在删除功能中我必须做什么。
这是我的结构:
struct ClientList {
struct ClientList *Next;
int socket;
char username[100];
int count;
FILE *file;
} ;
这里是添加节点的插入函数
void insert(struct ClientList *newItem,int new_s) {
pthread_mutex_lock(&mymutex);
struct ClientList *temp = (struct ClientList *) malloc(sizeof(struct ClientList)) ;
temp->socket = new_s;
temp->Next = head;
head = temp;
pthread_mutex_unlock(&mymutex);
}//insert function
这里是删除函数
int del(struct ClientList *temp,struct ClientList *newItem) {
struct ClientList *cur = head;
if (temp == head) {
head = temp->Next;
free(temp);
return 0;
}//if
else {
while (cur) {
if (cur->Next == temp) {
cur->Next = temp->Next;
free(temp);
}//if
cur = cur->Next;
}//while
}//else
}//del
对于第一个节点我没有问题,但对于所有其他节点它不起作用。
我必须添加我的广播功能,我用它来向所有人广播来自任何客户端的任何消息。 这是广播代码:
void broadcast(struct ClientList* temp,char buf[MAX_LINE],struct ClientList * newItem) {
int len;
pthread_mutex_lock(&mymutex);
for(temp = head; temp != NULL; temp =temp->Next) {
if (temp->socket ! =newItem->socket) {
buf[MAX_LINE-1]= '\0';
len = strlen(buf) + 1;
send(temp->socket, buf, len, 0);
}//if
}//for
pthread_mutex_unlock(&mymutex);
}//broadcast
最佳答案
您在第二个 if 中进行赋值,而不是进行比较。应该是:
if(cur->Next == temp)
不是
if(cur->Next=temp)
关于c - 从c中的链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15193013/