Windows Mail Slots (mailslot)
from the second edition of Windows network programming Chinese
Advantages: broadcasts a message to one or more computers over the network.
Disadvantages: Only allow from the client to the server, establish an unreliable one-way data communication. does not provide security for data reliability propagation. Mail slots are designed around the Windows file system interface. Client and server applications require the use of standard WIN32 file system I/O functions, such as ReadFile and WriteFile, to send and receive data on mail slots while leveraging the naming conventions of the Win32 file system.
the name of the mail slotMessage slot identification follows the following naming convention://server/mailslot/[path]name The first part//server the corresponding server name, creates a message slot on it and runs the server program on it. The value can be a decimal point (.), an asterisk (*), a domain name, or a real server name. The so-called "domain" is a combination of workstations and servers that share the same group name. The second part of the/mailslot is a fixed string. The third part/[path]name, where "path" represents a path, which can refer to a multilevel directory. The following are all legal names://oreo/mailslot/mymailslot//testserver/mailslot/cooldirectory/funtest/anothermailslot//./mailslot/ Easymailslot//*/mailslot/myslot
the length of the messageMail slots are usually "no connection" to send "datagram" (Datagram), do not require the other party to provide confirmation of the receipt of the package. There is no connection to broadcast messages from one client to multiple servers. Exception: In Windows NT and Windows 2000, if the message is longer than 424 bytes, it must be transmitted using a "connection-oriented" protocol instead of using a non-connected "datagram" form. This also makes it impossible to broadcast a message from the client to multiple servers. For a "connection-oriented" transmission, it is bound to be "one-to-one" communication: a client to a server.
compilation of the applicationWhen you use VC + + 6.0 to prepare the mail slot application, you must include the Winbase.h header file. If you already include Windows.h, you can save Winbase.h. The application needs to be linked with Kernel32.lib (VC + + 6.0 default configuration).
Error codeIn mail slot application development, all WIN32 API functions (except CreateFile and Createmailslot) return 0 when the call fails. The two APIs createfile and Createmailslot return Invalid_handle_value (Invalid handle value). Call failure You can use the GetLastError function to accept special information related to this failure.
Basic client/serverServer process: Creates a message slot that is the only process that can read data from the message slot. Client: Responsible for opening the message slot "instance" is the only process that can write data to it.
Server:1. Create a message slot with the Createmailslot API function and obtain a handle. 2. Call the ReadFile API function to receive data from any client using an existing mail slot handle. 3. Close the mail slot handle with the CloseHandle function. Create message Slots: HANDLE createmailslot (LPCTSTR lpname,//Specify the name of the mail slot, such as//./mailslot/[path]name, where the decimal point represents the server-based machine (cannot create a mail slot for the remote computer). DWORD nmaxmessagesize,//The maximum message length (in bytes) that can be written to the message slot, the client message is larger than the value the server does not accept the message, or 0 to receive any length of message. DWORD lreadtiemout,//Wait mode and no wait mode, Mailslot_wait_forever waits indefinitely, 0 returns immediately, and other values in milliseconds. Lpsecurity_attributes lpsecurityattributes//access control permissions, usually this null); Read message slots data: BOOL ReadFile (HANDLE hfile,// The message slot handle returned by Createmailslot LPVoid lpbuffer,//and nNumberOfBytesToRead together determine how much data can be read from the message slot, and Createmailslot in Nmaxmessagesize. If the DWORD nnumberofbytestoread,//is not large enough, the ReadFile call fails to return a error_insufficient_buffer error. Lpword lpnumberofbytesread,//The actual number of bytes read in after the read is completed. The lpoverlapped lpoverlapped//can take the Win32 overlapped I/O mechanism, is set to null if not adopted, and blocks until the data is read in after the call. );
- Server.cpp
- Server mail slots for receiving broadcast information sent by customers
- #include <windows.h>
- #include <stdio.h>
- int main ()
- {
- HANDLE mailslot;
- Char buffer[256];
- DWORD Numberofbytesread;
- //create the Mailslot
- Mailslot = Createmailslot ("////.//mailslot//myslot", 0,
- Mailslot_wait_forever,null);
- if (Invalid_handle_value = = mailslot)
- {
- printf ("Failed to create a mailslot%d/n", GetLastError ());
- return-1;
- }
- //read data from the Mailslot forever!
- While (0! = ReadFile (mailslot, buffer,, &numberofbytesread, NULL))
- {
- printf ("%.*s/n", numberofbytesread,buffer);
- }
- CloseHandle (mailslot);
- return 0;
- }
Client: References and writes to an existing message slot. 1. Using CreateFile, open a reference handle to the message slot to which you want to transfer data. 2. Call WriteFile to write data to the mail slot. 3. When the data is written, close the Open mail slot handle with CloseHandle. Open a reference handle to the message slot: HANDLE CreateFile (lpctstr lpfilename,//mail slot name DWORD dwdesiredaccess,//must be Generic_write, Because the client can only write data to the server. The DWORD dwsharedmode,//must be file_share_read to run the server in the mail slot to open and read operations. Lpsecurity_attributes lpsecurityattributes,//is set to null. The DWORD dwcreationdisposition,//is set to Open_existing, the server is local and no message slot calls are created, and the server is remote and the parameter is meaningless. DWORD dwflagsandattributes,//set to File_attribute_normalhandle htemplatefile//set to null); Write data: BOOL WriteFile (HANDLE hfile ,//createfile returns a reference handle lpcvoid the string length (a maximum length of 64KB) sent by the string DWORD nnumberofbytestowrite,//lpbuffer,//. Lpdword the number of bytes of data actually sent after the lpnumberofbyteswritten,//operation has completed. lpoverlapped lpoverlapped//mail Slot is "No connection" data transfer, WriteFile function is not waiting on I/O call, so the parameter is set to NULL
- Client.cpp
- The client is used to send broadcast data to the server
- #include <windows.h>
- #include <stdio.h>
- int main (int argc, char *argv[])
- {
- HANDLE mailslot;
- DWORD Byteswritten;
- CHAR servername[256];
- //Accept the server name from the command line to send data to
- if (argc < 2)
- {
- printf ("usage:client <server name>/n");
- return-1;
- }
- sprintf (ServerName, "////%s//mailslot//myslot", argv[1]);
- Mailslot = CreateFile (ServerName, Generic_write,
- File_share_read, NULL, open_existing, file_attribute_normal,null);
- if (Invalid_handle_value = = mailslot)
- {
- printf ("WriteFile failed with error%d/n", GetLastError ());
- return-1;
- }
- if (0 = = WriteFile (Mailslot, "This is a test", &byteswritten,null))
- {
- printf ("WriteFile failed with error%d/n", GetLastError ());
- return-1;
- }
- printf ("wrote%d byteds/n", byteswritten);
- CloseHandle (mailslot);
- return 0;
- }
Server other Apigetmailslotinfo: Once messages can be passed on the message slot, the Getmailslotinfo function is responsible for getting the message length information, and using this function, the program can dynamically adjust its buffer size for variable-length entry messages. Getmailslotinfo can also be used to "poll" incoming data. BOOL getmailslotinfo (HANDLE Hmailslot,//createmailslot Returns a handle to the message slot. Lpdword lpmaxmessagesize,//Sets how large a message can be written to the message slot (in bytes). Lpdword lpnextsize,//The length of the next message, it may return mailslot_no_message, indicating that there are currently no messages waiting to be received. Lpdword the number of waiting messages that are read into the lpmessagecount,//function when it returns. Lpdword the length of time, in milliseconds, that lpreadtimeout//waits for a message to be written. ); Setmailslotinfo: Sets the timeout value for the message slot. A read operation that exceeds this value no longer waits for incoming messages. BOOL setmailslotinfo (HANDLE Hmailslot,//createmailslot Returns a handle to the message slot. The DWORD lreadtimeout//has milliseconds to specify the maximum time a read operation waits for a message to be written, 0, no message to return immediately; Mailslot_wait_forever to wait forever. );
cannot cancel I/O requests that are "blocked"For Windows 95 and Windows 98, the Mail slot server accepts data with ReadFile, and if a message slot is created with the MAILSLOT_WAIT_FOREVER flag, the read request waits until there is data available. If the ReadFile request has not been completed and the server application is suddenly aborted, the application will be "suspended" or "blocked" forever. Only restart Windows to cancel. To solve this problem, you can have the server open a handle to its own message slot in a separate thread. and data is taken in the main thread when the exit is required to terminate the read operation in the suspended body.
- Server2.cpp
- Non-blocking server mail slots for receiving broadcast information sent by customers
- #include <windows.h>
- #include <stdio.h>
- #include <conio.h>
- BOOL stopprocessing;
- DWORD WINAPI servemailslot (lpvoid lpparameter);
- void Sendmessagetomailslot (void);
- int main ()
- {
- DWORD ThreadId;
- HANDLE Mailslotthread;
- stopprocessing = FALSE;
- Mailslotthread = CreateThread (Null,0,servemailslot,
- Null,0,&threadid);
- printf ("Press a key to stop the server/n");
- _getch ();
- //mark the stopprocessing flag to TRUE so, when ReadFile
- //break, our server thread would end
- stopprocessing = TRUE;
- //send A message to our mailslot to break the ReadFile call
- //in Our server
- Sendmessagetomailslot ();
- //wait for the service thread to finish
- if (wait_failed = = WaitForSingleObject (Mailslotthread, INFINITE))
- {
- printf ("WaitForSingleObject failed with error%d/n", GetLastError ());
- return-1;
- }
- return 0;
- }
- This function was the Mailslot server worker function to
- Process all incoming mailslot I/O
- DWORD WINAPI servemailslot (lpvoid lpparameter)
- {
- Char buffer[2048];
- DWORD Numberofbytesread;
- DWORD Ret;
- HANDLE mailslot;
- Mailslot = Createmailslot ("////.//mailslot//myslot", 2048,mailslot_wait_forever,null);
- if (Invalid_handle_value = = mailslot)
- {
- printf ("Failed to create a mailslot%d/n", GetLastError ());
- return-1;
- }
- While (0! = (Ret = ReadFile (mailslot,buffer,2048,&numberofbytesread,null)))
- {
- if (stopprocessing)
- Break ;
- printf ("Received%d bytes/n", numberofbytesread);
- }
- CloseHandle (mailslot);
- return 0;
- }
- The Sendmessagetomailslot function is designed to send a
- Simple message to our servers so we can break the blocking
- ReadFile API Call
- void Sendmessagetomailslot ()
- {
- HANDLE mailslot;
- DWORD Byteswritten;
- Mailslot = CreateFile ("////.//mailslot//myslot", Generic_write,
- File_share_read,null,open_existing,file_attribute_normal,null);
- if (Invalid_handle_value = = mailslot)
- {
- printf ("CreateFile failed with error%d/n", GetLastError ());
- return;
- }
- if (0 = = WriteFile (mailslot, "STOP", 4, &byteswritten, NULL))
- {
- printf ("WriteFile failed with error%d/n", GetLastError ());
- return;
- }
- CloseHandle (mailslot);
- }
"Go" Windows Mail slots (mailslot)