-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;
}
查看你書中用來學習網絡編程的章節,它解釋瞭如何使用非阻塞套接字以及poll()或select()系統調用。 –
謝謝!通過材料,並問了一些問題,我終於明白我做錯了什麼! –