2017-12-03 4 views
1

N 개를 수신하고이 데이터 배치를 처리하여 모든 클라이언트에게 "완료"한 답장을 보낼 때까지 여러 클라이언트의 메시지를 수락하는 서버를 작성하려고합니다.소켓 : 여러 클라이언트에 메시지 보내기

클라이언트에서 데이터를받은 직후에 클라이언트에 "완료"메시지를 보내면이 코드가 제대로 작동합니다. 어떻게하면 모든 클라이언트를 "저장"하고 나중에 배치를 처리 한 후에 메시지를 각각 보낼 수 있습니까?

while (true) { 
    listen(sock, 1000); 
    newsock = accept(sock, (struct sockaddr *) &cli_addr, &clilen); 
    n = read(newsock, buffer, read_len); 
    if (n < 0) { 
     cout << "ERROR reading from the socket" << endl; 
     continue; 
    } 
    memcpy(data + (msg_count * tuple_size), buffer, tuple_size); 
    n = write(newsock, "done\n", 5); //sending the message to the current client 
    msg_count++; 
    if (msg_count >= batch_size) { 
     msg_count = 0; 
     doSomethingWithTheData(data); 
     //I want to send the message to all the clients here 
    } 
    bzero(buffer, read_len); 
} 
+0

쿠키 설정을 시도 했습니까? – Arash

+0

@ArashMohammadi 아니, 나는 그들을 시도하지 않았다, 나는 그것에 대해 지금 읽을거야. 서버와 모든 클라이언트가 동일한 PC에있는 경우 쿠키가 작동합니까? – vgeclair

+0

클라이언트가 하나 이상의 메시지를 보낼 수 있다면,'select' 나'epoll'을 조사 할 수 있습니다. – user4581301

답변

1

다음과 같이 시도해보십시오. (3) 새로운 프로그램에서 사용 memset 함수 :

while (true) { 
    std::list<int> socks; 
    listen(sock, 1000); 
    newsock = accept(sock, (struct sockaddr *) &cli_addr, &clilen); 
    n = read(newsock, buffer, read_len); 
    if (n < 0) { 
     cout << "ERROR reading from the socket" << endl; 
     continue; 
    } 
    memcpy(data + (msg_count * tuple_size), buffer, tuple_size); 
    socks.push_back(newsock); 
    msg_count++; 
    if (msg_count >= batch_size) { 
     msg_count = 0; 
     doSomethingWithTheData(data); 

     //I want to send the message to all the clients here 
     msg_count -= socks.size(); 
     while (!socks.empty()) { 
      newsock = socks.front(); 
      n = write(newsock, "done\n", 5); //sending the message to the current client 
      close(newsock); 
      socks.pop_front(); 
     } 
    } 
    bzero(buffer, read_len); 
} 

FYI bzero() 함수는 사용되지 않으며 (POSIX.1-2001에 LEGACY으로 표시). POSIX.1-2008은 bzero()의 지정을 제거합니다

+0

수정하십시오. 어쨌든 이런 일을해야 할 것입니다, vgeclair, 왜냐하면 현재는 양말을 자유롭게하지 않고 할당하기 때문입니다. – user2328447

+0

방금 ​​시도했지만이 줄에 "깨진 파이프"오류가 나타납니다. 'n = write (sock, "done \ n", 5); ' 'sock '을 'newsock'이 아닌리스트? 항상 같은 가치가있는 것 같습니다. – vgeclair

+0

@vgeclair가 정확합니다. 'sock'은 당신이 듣고있는 소켓이지 클라이언트에 연결된 소켓이 아닙니다. – user4581301

-1

zeroMq를 시도 했습니까? 예 : http://zguide.zeromq.org/cpp:rrworker

+0

아니, 나는 그것을 시험하지 않고 있었다. 여러 고객을 기억하는 데 어떻게 도움이됩니까? – vgeclair

+0

내 생각은 클라이언트가 프런트 엔드 소켓에 연결하여 일괄 작업자에게 전달하는 n 클라이언트가 요청 - 응답 패턴을 확장하는 것이 었습니다. 작업자가 n 클라이언트에 작업 프런트 엔드 소켓 응답을 마친 후 – fbalicchia

관련 문제