2014-11-14 2 views
0

소수의 클라이언트 만 받아 들여야하는 C 언어를 사용하여 서버 코드를 프로그래밍하고 있습니다. 추가 클라이언트가 도착하면 서버는 이전 클라이언트 중 하나가 종료 될 때까지 클라이언트를 대기시킵니다.서버는 n 개의 클라이언트 만 수락 할 수 있습니다.

예를 들어 (서버는 10 개의 클라이언트 만 허용 할 수 있습니다. 새 클라이언트가 도착하면 서버는 10 개의 클라이언트 중 하나가 종료 될 때까지 클라이언트를 대기시킵니다.

함수를 사용하고 listen() 함수 이후에 accept() 전에 사용해야하고 클라이언트 수를 계산하는 값을 만들지 만 올바르게 사용하는 방법을 모르겠습니다.

아무에게도 나에게 간단한 힌트를 줄 수 있습니까?

signal()를 사용할 필요가

+0

이전에 해봤습니까? –

+0

조회 '멀티 스레딩'과 특히 pthreads – jev

+0

'그 클라이언트를 기다려라 .' ... 어떻게? 여기서 정확히 '기다리는 것'으로 간주되는 것은 무엇입니까? –

답변

0

입니다 ,,,,,, 주셔서 감사합니다. 예 :

#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 

main() 
{ 
    int s = socket(PF_INET, SOCK_STREAM, 0); // server socket 
    if (s   == -1) return perror("socket"), 1; 
    if (listen(s, 0) == -1) return perror("listen"), 1; 
    const int n = 10; // number of clients allowed to be served 
    fd_set fds, rfds; 
    FD_ZERO(&fds); 
    FD_SET(s, &fds); // initially, set of sockets holds server 
    int nfds = s+1, fd, clients = 0; 
    while (rfds = fds, select(nfds, &rfds, NULL, NULL, NULL) > 0) 
     for (fd = 0; fd < nfds; ++fd) 
      if (FD_ISSET(fd, &rfds)) // see which sockets of set are ready 
       if (fd == s)   // is it the server socket? 
       { // yes, so it is a client's connection request 
        printf("new client request "); 
        struct sockaddr_in sa = { AF_INET, 0, INADDR_ANY }; 
        socklen_t sal = sizeof sa; 
        int c = accept(s, (struct sockaddr *)&sa, &sal); 
        if (c == -1) return perror("accept"), 1; 
        FD_SET(c, &fds); if (nfds <= c) nfds = c+1; // add client 
        printf("accepted (fd=%d) # clients now %d\n", c, ++clients); 
        if (clients == n) // allowed number hit? 
         puts("Further client requests will be ignored."), 
         FD_CLR(s, &fds); // don't watch server now 
       } 
       else 
       { // this is a client's message or termination 
        printf("client fd=%d: ", fd); 
        char buf[BUFSIZ]; 
        size_t count = read(fd, buf, sizeof buf); 
        if (count > 0) fwrite(buf, 1, count, stdout); 
        else 
        { // no more data from client, so close the connection 
         close(fd); 
         FD_CLR(fd, &fds); // remove client from watch set 
         printf("closed, # clients now %d\n", --clients); 
         if (clients == n-1) // went just below allowed number? 
          FD_SET(s, &fds), // watch server again 
          puts("New client requests will be accepted again."); 
        } 
       } 
    return perror("select"), 1; 
} 

참고 :이 프로그램은 임의의 무료 포트에 바인딩됩니다.이 포트는 전자 메일에서 찾을 수 있습니다. 지. netstat -tlp. 물론 특정 주소와 포트에 bind()을 사용할 수도 있습니다. 어떤 경우 든 e로 테스트 할 수 있습니다. 지. nc hostname port.