MFC基於select模型的套接字類之伺服器(5)

2021-08-10 10:42:25 字數 1818 閱讀 7819

在定義了執行緒函式之後,回到ctcpsocket_server類的startserver()函式中。接下來通過

createthread()

函式建立

threadfunc_startserver()

的執行緒,接受來自客戶端的連線。

(1)createthread()函式

該函式的作用是建立新執行緒,其格式為

handle winapi createthread(

lpsecurity_attribute lpthreadattributes

, size_t dwstacksize

, lpthread_start_routine lpstartaddress

, lpvoid lpparameter

, dword dwcreateflags

, lpdword lpthreadid

);

其中,引數lpthreadattributes

指定了執行緒的控制代碼是否能被子執行緒繼承,如果該引數設定為

null

,則表示不能被繼承;

dwstacksize

指定了新建立執行緒棧的初始大小,如果該引數設定為

0,則表示棧的初始大小為預設值;

lpstartaddress

是執行緒函式的位址;

lpparameter

表示執行緒函式的引數;

dwcreateflags

指定了執行緒建立時的控制標誌,如果該引數設定為

0,則表示執行緒在建立後馬上執行;

lpthreadid

用於儲存建立執行緒的

id,如果不需要執行緒

id,可將該引數設定為

null

。如果建立執行緒成功,則返回值為新建立執行緒的控制代碼,否則返回值為

null

。(2)建立接受客戶端連線的執行緒

在startserver()函式中,通過以下**建立接受客戶端連線的執行緒

m_acceptthread_handle = createthread(null, 0, (lpthread_start_routine)ctcpsocket_server::threadfunc_startserver, this, 0, null);
其中,threadfunc_startserver

是「2.3.3

定義執行緒函式」中定義的執行緒函式;

this

表示ctcpsocket_server

類物件的指標,threadfunc_startserver()

函式通過該指標可以訪問ctcpsocket_server

類的非靜態成員。m_acceptthread_handle

是ctcpsocket_server

類型別為handle

的成員變數,用來儲存執行緒的控制代碼。

在接收了客戶端連線之後,服務端接下來要接收客戶端傳送過來的資料。由於不知道客戶端什麼時候傳送資料,所以服務端需要建立乙個新的執行緒,一直準備接收資料。在newconnect()函式中建立接收資料執行緒。在前文中已經提到,

newconnect()

函式在startserver()

(1)宣告接收資料的執行緒函式

在「2.3.3

定義執行緒函式」中提到,執行緒函式必須是全域性函式或者是類的靜態函式。首先,為ctcpsocket_server類新增乙個名為threadfunc_recvdata()的靜態函式,其格式為

static dword threadfunc_recvdata(lpvoid lpparameter);

基於select模型的server

前面一篇介紹了io模型。其中重點介紹了io多路轉接中的三種模型,包括了select,poll,epoll三種。下面就是基於select模型編寫的伺服器與客戶機,兩者可以進行互動。伺服器端 k include include include include include include includ...

基於Select模型的UDP TCP混合程式設計

selecttestserver.cpp 定義控制台應用程式的入口點。tcp udp復用server select非阻塞模式 ip 127.0.0.1 tcp port 5001 udp port 5000 include stdafx.h include pragma comment lib,ws...

基於事件套接字集合的select 模型

基於事件套接字集合的select 模型 select 選擇 模型是winsock 中最常見的i o 模型。之所以稱其為 select 模型 是由於它的 中心思想 便是利用select 函式,實現對i o 的管理!最初設計該模型時,主要面向的是某些使用unix 作業系統的計算機,它們採用的是berke...