"Go" Windows Mail slots (mailslot)

Source: Internet
Author: User
Tags readfile

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. );
  1. Server.cpp
  2. Server mail slots for receiving broadcast information sent by customers
  3. #include <windows.h>
  4. #include <stdio.h>
  5. int main ()
  6. {
  7. HANDLE mailslot;
  8. Char buffer[256];
  9. DWORD Numberofbytesread;
  10. //create the Mailslot
  11. Mailslot = Createmailslot ("////.//mailslot//myslot", 0,
  12. Mailslot_wait_forever,null);
  13. if (Invalid_handle_value = = mailslot)
  14. {
  15. printf ("Failed to create a mailslot%d/n", GetLastError ());
  16. return-1;
  17. }
  18. //read data from the Mailslot forever!
  19. While (0! = ReadFile (mailslot, buffer,, &numberofbytesread, NULL))
  20. {
  21. printf ("%.*s/n", numberofbytesread,buffer);
  22. }
  23. CloseHandle (mailslot);
  24. return 0;
  25. }
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
  1. Client.cpp
  2. The client is used to send broadcast data to the server
  3. #include <windows.h>
  4. #include <stdio.h>
  5. int main (int argc, char *argv[])
  6. {
  7. HANDLE mailslot;
  8. DWORD Byteswritten;
  9. CHAR servername[256];
  10. //Accept the server name from the command line to send data to
  11. if (argc < 2)
  12. {
  13. printf ("usage:client <server name>/n");
  14. return-1;
  15. }
  16. sprintf (ServerName, "////%s//mailslot//myslot", argv[1]);
  17. Mailslot = CreateFile (ServerName, Generic_write,
  18. File_share_read, NULL, open_existing, file_attribute_normal,null);
  19. if (Invalid_handle_value = = mailslot)
  20. {
  21. printf ("WriteFile failed with error%d/n", GetLastError ());
  22. return-1;
  23. }
  24. if (0 = = WriteFile (Mailslot, "This is a test", &byteswritten,null))
  25. {
  26. printf ("WriteFile failed with error%d/n", GetLastError ());
  27. return-1;
  28. }
  29. printf ("wrote%d byteds/n", byteswritten);
  30. CloseHandle (mailslot);
  31. return 0;
  32. }
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.
  1. Server2.cpp
  2. Non-blocking server mail slots for receiving broadcast information sent by customers
  3. #include <windows.h>
  4. #include <stdio.h>
  5. #include <conio.h>
  6. BOOL stopprocessing;
  7. DWORD WINAPI servemailslot (lpvoid lpparameter);
  8. void Sendmessagetomailslot (void);
  9. int main ()
  10. {
  11. DWORD ThreadId;
  12. HANDLE Mailslotthread;
  13. stopprocessing = FALSE;
  14. Mailslotthread = CreateThread (Null,0,servemailslot,
  15. Null,0,&threadid);
  16. printf ("Press a key to stop the server/n");
  17. _getch ();
  18. //mark the stopprocessing flag to TRUE so, when ReadFile
  19. //break, our server thread would end
  20. stopprocessing = TRUE;
  21. //send A message to our mailslot to break the ReadFile call
  22. //in Our server
  23. Sendmessagetomailslot ();
  24. //wait for the service thread to finish
  25. if (wait_failed = = WaitForSingleObject (Mailslotthread, INFINITE))
  26. {
  27. printf ("WaitForSingleObject failed with error%d/n", GetLastError ());
  28. return-1;
  29. }
  30. return 0;
  31. }
  32. This function was the Mailslot server worker function to
  33. Process all incoming mailslot I/O
  34. DWORD WINAPI servemailslot (lpvoid lpparameter)
  35. {
  36. Char buffer[2048];
  37. DWORD Numberofbytesread;
  38. DWORD Ret;
  39. HANDLE mailslot;
  40. Mailslot = Createmailslot ("////.//mailslot//myslot", 2048,mailslot_wait_forever,null);
  41. if (Invalid_handle_value = = mailslot)
  42. {
  43. printf ("Failed to create a mailslot%d/n", GetLastError ());
  44. return-1;
  45. }
  46. While (0! = (Ret = ReadFile (mailslot,buffer,2048,&numberofbytesread,null)))
  47. {
  48. if (stopprocessing)
  49. Break ;
  50. printf ("Received%d bytes/n", numberofbytesread);
  51. }
  52. CloseHandle (mailslot);
  53. return 0;
  54. }
  55. The Sendmessagetomailslot function is designed to send a
  56. Simple message to our servers so we can break the blocking
  57. ReadFile API Call
  58. void Sendmessagetomailslot ()
  59. {
  60. HANDLE mailslot;
  61. DWORD Byteswritten;
  62. Mailslot = CreateFile ("////.//mailslot//myslot", Generic_write,
  63. File_share_read,null,open_existing,file_attribute_normal,null);
  64. if (Invalid_handle_value = = mailslot)
  65. {
  66. printf ("CreateFile failed with error%d/n", GetLastError ());
  67. return;
  68. }
  69. if (0 = = WriteFile (mailslot, "STOP", 4, &byteswritten, NULL))
  70. {
  71. printf ("WriteFile failed with error%d/n", GetLastError ());
  72. return;
  73. }
  74. CloseHandle (mailslot);
  75. }

"Go" Windows Mail slots (mailslot)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.