2017-02-15 33 views
-2

我有EchoServer.cpp代码下面,它允许我设置一个服务器,并与两个提示窗口,我可以与服务器通信,将返回相同的文本我键入。如何修改C++服务器代码以顺序处理多个客户端?

实施例:

输入>您好
输出>您好

然而,服务器仅允许一个用户同时连接,并且如果在用户断开连接(关闭提示) ,服务器会自动关闭。我被告知只能修改几行(不需要使用多线程)来使其工作。

为了让服务器不断开和下一个用户等到第一个用户断开连接(关闭提示符),我需要做些什么?

如果可能的话,解释或来源网页,所以我可以阅读更多关于将有所帮助。

#include <iostream> 
using std::cout; 
using std::cin; 

#include <iomanip> 
using std::setw; 
using std::endl; 

#include "../api/cnaiapi.h" 

int main(int argc, char *argv[]) { 
    /** Buffer size.     */ 
    const int BUFFER_SIZE = 256; 
    /** Socket descriptor for service. */ 
    connection conn; 
    /** Length of buffer.    */ 
    int len; 
    /** Input buffer.     */ 
    char buff[BUFFER_SIZE]; 

    if (argc != 2) { 
     /**line to send formatted output to a stream - RC**/ 
     (void) fprintf(stderr, "usage: %s <appnum>\n", argv[0]);   
     exit(1); 
    } 

    /* Verify that the user passed the command line arguments.*/ 
    if (argc != 2) { 
     cout << "\n\tUsage: " << argv[0] 
      << " <appnum or port#>" 
      << "\n\tExample:" 
      << "\n\t" << argv[0] 
      << " 7" 
      << "\n\n\t(Start the server on port number 7" 
      << "\n\n" << endl; 
     exit(1); 
    } 

    /* Wait for a connection from an echo client, 
    * if no client connects exit in error. 
    */ 
/* conn = await_contact((appnum) atoi(argv[1])); 
    if (conn < 0) 
     exit(1); 
*/ 
    conn = await_contact((appnum)atoi(argv[1])); 
    if (conn < 0) 
     exit(1); 

    /* iterate, echoing all data received until end of file */ 
    while ((len = recv(conn, buff, BUFFER_SIZE, 0)) > 0) 
     (void) send(conn, buff, len, 0); 
    send_eof(conn); 

    return 0; 
} 
+2

查看你书中用来学习网络编程的章节,它解释了如何使用非阻塞套接字以及poll()或select()系统调用。 –

+0

谢谢!通过材料,并问了一些问题,我终于明白我做错了什么! –

回答

0

再次阅读材料,并意识到我必须在代码结束时包含一段时间。

While(true) { 
    (void) printf("Server start."); 
    //Some code 

    //Some code 
    (void) printf("Client Connected."); 
} 
send_eof(conn); 
相关问题