2013-03-04 72 views
0

我试图在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 
+0

除了已经做出2个回答之外,请确保您的删除功能采用互斥体。您的插入功能可以实现,您的删除功能也应该如此。 – Celada 2013-03-04 01:16:08

回答

4

你在你的第二个如果不这样做比较分配。它应该是:

if(cur->Next == temp) 

if(cur->Next=temp) 
3

最有可能的,因为只使用一个等号的琐碎错误通缉两名时:

if(cur->Next=temp) 

应该是:

if(cur->Next==temp) 

(也删除分机ra参数是不需要的“del”!)

提示:如果您使用的是良好的编译器,例如gcc,并且启用了所有警告-Wall,那么当您犯这个错误时它会给你一个警告。

+0

谢谢。但它只是复制问题。 – 2013-03-04 02:03:07

0

虽然你实际的问题已经回答了,这里是你的删除功能一对夫妇的补充意见:

  1. 一旦你找到了条目被删除,没有理由继续搜索列表。我会在第二个free之后添加break声明。
  2. 在函数结尾处没有return 0语句。因此,如果要删除的条目不在列表的头部,则该函数的返回值将是未定义的。

这些都不会导致您的程序发生故障(除非您正在检查返回值),但这些都很好,以纠正。

+0

非常感谢你 – 2013-03-04 02:04:36

+0

我的问题还没有回答 – 2013-03-04 02:09:45

+0

@pejman你的代码适合我:[Link](http://codepad.org/yjcG81LL) – ccKep 2013-03-04 04:42:02