2017-08-18 36 views
0

我正在使用C++的客戶端/服務器解決方案。通過建立TCP連接只發送一次Recv從客戶端到服務器套接字

從客戶端,我發送數據到我的服務器,並從這臺服務器發送到另一臺服務器。我可以配置端口和IP地址,並且能夠成功發送。

但是,另一臺服務器(不在我的身邊)只需要從我身邊建立一個TCP連接,之後只需要發送和接收數據。

如果我連接了兩次(同時從兩個客戶端說出),則表明連接被拒絕。

部分代碼如下所示:

while ((len = stream->receive(input, sizeof(input)-1)) > 0) 
{ 
    input[len] = NULL; 
    //Code Addition by Srini starts here 

    //Client declaration 
    TCPConnector* connector_client = new TCPConnector(); 
    printf("ip_client = %s\tport_client = %s\tport_client_int = %d\n", ip_client.c_str(), port_client.c_str(),atoi(port_client.c_str())); 
    TCPStream* stream_client = connector_client->connect(ip_client.c_str(), atoi(port_client.c_str())); 

    //Client declaration ends 
    if (stream_client) 
    { 
     //message = "Is there life on Mars?"; 
     //stream_client->send(message.c_str(), message.size()); 
     //printf("sent - %s\n", message.c_str()); 

     stream_client->send(input, sizeof(input)); 
     printf("sent - %s\n", input); 
     len = stream_client->receive(line, sizeof(line)); 
     line[len] = NULL; 
     printf("received - %s\n", line); 
     delete stream_client; 
    } 

    //Code Additon by Srini ends here 

    stream->send(line, len); 
    printf("thread %lu, echoed '%s' back to the client\n", 
     (long unsigned int)self(), line); 
} 

完整螺紋代碼,其中從客戶端接收,發送到服務器,從服務器接收,並且發送到客戶端在下面的鏈接被示出:

https://pastebin.com/UmPQJ70w

如何更改我的設計流程?即使在客戶端/服務器程序的基本圖中。當客戶端調用connect()時,服務器每次調用accept(),然後發送/接收。那麼,可以做些什麼來修改流程,以便客戶端只能連接一次?

回答

0

您的中間服務器(充當代理,因此可以稱之爲)需要維護到其他服務器的單個連接,並與其代理消息並行地發送到您的代理和客戶端之間的消息傳遞。

我會建議創建一個單獨的線程,其唯一的任務是保持與其他服務器的連接,並使用它發送/接收消息。

當客戶端向您的代理髮送消息時,將消息放置在某個線程安全隊列中。讓線程定期檢查隊列並將任何排隊的消息發送到其他服務器。

當其他服務器向您的代理髮送消息時,該線程可以接收該消息並將其轉發給相應的客戶端。

相關問題