日期:2014-05-16  浏览次数:20616 次

局域网聊天的linux c C/S模式遇到问题。
最近刚开始接触编程,http://blog.chinaunix.net/uid-25530360-id-351062.html(我不是托,因为是参考这里的)看到这里的程序感兴趣就想模仿一个。在粗略看了一遍源码的情况下自己模仿写了一个,但是依然出现问题,改了一个多星期不成功,索性改成几乎跟别人写的基本没区别了。但还是不行,只能恳请各各位朋友指点指点啦。下面是源码(只有第一个链接到服务器的客户端可以说话,其他的只能接收,而不能发话)
////////////////////////////////////////////////////
客户端:
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<strings.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#define MAXLINE 80
void main()
{
  int fd,n,p=0;
  char c,x,buf[MAXLINE];
  struct sockaddr_in aip;
  pid_t pid;
  fd=socket(AF_INET,SOCK_STREAM,0);
  bzero(&aip,sizeof(aip));
  aip.sin_family = AF_INET;
  inet_pton(AF_INET,"127.0.0.1",&aip.sin_addr);
  aip.sin_port=htons(5678);
  // inet_aton("127.0.0.1",&aip.sin_addr);
  connect(fd,(struct sockaddr *)&aip,sizeof(aip));
  while(1)
    {
      pid=fork();
      if(pid < 0)
{
  printf("fork failed");
  exit(1);
}
      if(pid == 0)
{    
  p=read(fd,buf,MAXLINE);
  if(p==0)
    printf("the other client has been shutdown");
  else
  write(STDOUT_FILENO,buf,p); 
  //  exit(0);  
}
      else
{
  {
    fgets(buf,MAXLINE,stdin);
    write(fd,buf,strlen(buf));
    //  close(fd);
  }
}      
    }   
  close(fd); 
}

////////////////////////////服务器端
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<strings.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<string.h>
#include<sys/select.h>
#include<sys/time.h>
#define BACKLOG 20
#define MAXLINE 80
int main()
{
  int fd,secondefd,i=0,client[1024],j=0,sockfd,k=0,counti=-1,max=-1,clientfd=0,p=0;
  struct sockaddr_in aip,hint;
  char c,buf[MAXLINE],str[INET_ADDRSTRLEN];;
  socklen_t sock_size;
  pid_t pid;
  fd_set jh,jh2;

  fd = socket(AF_INET,SOCK_STREAM,0);
  bzero(&aip,sizeof(aip));

  aip.sin_family=AF_INET;
  aip.sin_addr.s_addr=htonl(INADDR_ANY);
  aip.sin_port=htons(5678);

  bind(fd,(struct sockaddr *)&aip,sizeof(aip));
  listen(fd,BACKLOG);
  
  for(i=0;i<FD_SETSIZE;i++)
    client[i]=-1;
  max=fd;//最大文件描述符
  FD_ZERO(&jh);
  FD_SET(fd,&jh);
 
  while(1)
    {
       jh2=jh;
      // k=select(max+1,&jh,NULL,NULL,NULL);
       k=select(max+1,&jh2,NULL,NULL,NUL