我试图在C中做一个简单的聊天服务(套接字编程)。 服务器是并发的并且可以接受多个连接。我使用线程服务器和链接列表来保存套接字ID。一切工作正常,除了删除功能,我用来从链表中删除节点。无论何时客户端类型DONE
,我必须从链接列表中删除它的套接字ID,但它不能正常工作。有人能帮我弄清楚我在删除函数时该做些什么。从c中的链表中删除节点
这里是我的结构:
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;
}//else
}// while
}//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
除了已经做出2个回答之外,请确保您的删除功能采用互斥体。您的插入功能可以实现,您的删除功能也应该如此。 – Celada 2013-03-04 01:16:08