服务器 - 客户端cprogramming处理多个连接请求

时间:2013-04-28 11:44:47

标签: c connection client

想要建立服务器 - 客户端连接。我想将2个或更多客户端的数据发送到服务器。服务器需要收集此数据并将其写入数据库。问题是,如何使用fork(),getppid? GETPID?等待()?如何避免僵尸等。

int main( void ) 
{
  pid_t client_pid;
  pid_t wait(int *status);


  Socket server, client; 
  int bytes; 

  // open server socket 
  server = tcp_passive_open( PORT ); 

  while( 1 ) {     
    client = tcp_wait_for_connection( server ); 

    //create new process
    client_pid = fork();  
    printf("%d",client_pid); 
    //client must have id 
    if(client_pid >= 0){ 
    if(client_pid > 0){        //server



    }else{                //client

        bytes = tcp_receive( client, buffer, BUFSIZE);  
            printf("received message of %d bytes: %s\n", bytes, buffer); 

        // echo msg back to client 
        char buffer[] = "Send data ....put data here"; 
            tcp_send( client, (void*)buffer, bytes); 

            //sleep(1);    /* to allow socket to drain */ 
            tcp_close( &client );

    }
     }  
  }
  tcp_close( &server ); 
  return 0; 
}

对于客户我写了这个:

#define BUFSIZE 1024
#define SERVER_IP "127.0.0.1"
#define PORT 1234

unsigned char buffer[BUFSIZE];

int main( void ) {
  Socket client;
  int ret;
  char msg[] = "Hello there! Anyone?";

  // open TCP connection to the server; server is listening to SERVER_IP and PORT
  client = tcp_active_open( PORT, SERVER_IP );

  // send msg to server
  tcp_send( client, (void *)msg, strlen(msg)+1 );

  // get reply from server
  printf("\nanswer from server: ");
  while ( (ret = tcp_receive (client, buffer, BUFSIZE)) > 0 ) {
     printf("%s", buffer);
  }
  printf("\n");  

  // exit
  tcp_close( &client );
  return 1;
}

有人可以帮帮我吗?知道任何好的教程如何使用这个进程,线程等?

谢谢!

1 个答案:

答案 0 :(得分:0)

a)fork一个等待客户端连接的过程;

b)在主循环中等待僵尸进程;

c)检查How does fork() return for child process以获取fork的详细用法。