Windows網路程式設計基礎(1) 郵槽

2021-08-27 11:38:32 字數 2554 閱讀 7861

/*

2018-9-6 12:21:04

郵槽的使用

*/預備知識:createfile,readfile的使用

關鍵的函式 createmailslot 如果建立失敗 返回乙個無效的控制代碼值invilid_handle_value

用乙個有效的控制代碼建立了郵槽之後,便可開始資料的實際讀取。伺服器是唯一能從郵槽

讀入資料的程序

單項的 單線的資料傳輸

若想實現乙個郵槽,要求開發乙個伺服器應用,來負責郵槽的建立。下述步驟解釋了如

何編寫乙個基本的伺服器應用:

1) 用createmailslot api函式建立乙個郵槽控制代碼。

2) 呼叫readfile api函式,並使用現成的郵槽控制代碼,從任何客戶端接收資料。

3) 用closehandle這個api函式,關閉郵槽控制代碼。

可以看出,要開發乙個郵槽伺服器程式,只需使用極少的 api呼叫。伺服器程序是用

createmailslot這個api呼叫來建立郵槽的。定義如下

函式原型:

handle createmailslot(

lpctstr lpname,    //郵槽的名字

dword nmaxmessagesize, //收到訊息的長度設定,設定為0時表示可以接受任意長度的資料

dword lreadtimeout,    //0 或者 mailslot_wait_forever    讀取時間

lpsecurity_attributes lpsecurityattributes     // inheritance option;

}

服務端**:

// mailslot.cpp : 此檔案包含 "main" 函式。程式執行將在此處開始並結束。

//

#include #include #include int main()

char strshowresult[256] = ;

dword numberofbyteread;

//傳送資料

while (0 != readfile(mailslot, strshowresult, 256, &numberofbyteread, null))

system("pause");

return exit_success;

}

客戶端思想:

1) 使用createfile這個api函式,針對想向其傳送資料的郵槽,開啟指向它的乙個引用句

柄。2) 呼叫writefile這個api函式,向郵槽寫入資料。

3) 完成了資料的寫入後,用closehandle這個api函式,關閉開啟的郵槽控制代碼。

client1

#include #include #include int main()

dword bytestwritten;

std::string strinput;

while (1)

break;

}bool bflag = writefile(mailslot, strinput.c_str(), strinput.length(), &bytestwritten, null);

if (false == bflag)

strinput = "";

}std::cout << "wrote " << bytestwritten << " bytes\n";

closehandle(mailslot);

system("pause");

return exit_success;

}

服務端的乙個公升級版本

#include #include #include dword winapi servermialslot(lpvoid lpprameter);

void sendmessagetomainlslot();

bool stopprocessing;

int main()

system("pause");

return exit_success;

}dword __stdcall servermialslot(lpvoid lpprameter)

char buffer[2048];

dword numberofbyteread;

dword ret = readfile(mailslot, buffer, 2048, &numberofbyteread, null);

while (ret != 0)

closehandle(mailslot);

return exit_success;

}void sendmessagetomainlslot()

dword byteswritten;

if (0 == writefile(mailslot, "stop", 4, &byteswritten, null))

closehandle(mailslot);

}

可以同上面的client進行測試

WINDOWS簡單郵槽程式設計

服務端 include stdafx.h include include int tmain int argc,tchar argv dword numberofbytesread 0 if mailslot createmailslot l mailslot myslot 0,mailslot w...

網路程式設計基礎(1)

四個基礎類 1.dns類,2.ipaddress類,3.ipendpoint類,4.webclient類 1.dns類是乙個靜態類,它從internet網域名稱系統 dns 檢索關於特定主機的資訊。設計介面,然後是確定按鈕的 如下 using system using system.collecti...

網路程式設計 基礎1

使用語言 c語言 伺服器端的建立 server.c 建立套接字 socket 函式 函式原型 引數說明 繫結套接字 bind 函式 引數說明 建立監聽佇列 listen 函式 函式原型 引數說明 接收連線請求 accept 函式 函式原型 int main 給套接字繫結位址 需要用結構體來表示位址資...