This simple article will demonstrate how a
client application can find its
server in a network by using a Windows feature called Mailslot.
A Server which Broadcasts its IP and PORT
client application requires
server IP and PORT to get connected to it. However, when
server IP and/or PORT changes, all
clients must be aware, otherwise they cannot communicate anymore.
How Can We Make a Server Broadcast Data to a Network?
Windows platform offers a mechanism called Mailslot which is an IPC (Inter-Process Communication) where applications are able to send message-packets (DATAGRAMS) over the network either to a specific computer or to all computers in a specific domain.
A Simple Message Must Be Defined Before
Before showing how Mailslot can be implemented, it is worth mentioning that a simple message-packet must be recognized by both sides. The source code contains two projects
msclient. Both share ms_protocol.h that defines a simple message:
#define MS_MESSAGE_ID 0xaabbccdd
typedef struct _MS_MESSAGE_
MSMESSAGE is the message that the
server is going to broadcast every second. Notice that there is no answer to send back by the
client. It receives the message and uses information received to start a TCP/IP
stream connection with
Testing the Applications
The project was first coded by using the old VC++ 6 compiler. I have updated it to VS 2005. Both applications are console applications. If you have an older compiler, you won't have a problem in recreating the projects and building them.
The best way to test is on a network having
clients on different machines. But you can test on a single machine too.
server), you get a console window that shows IP and PORT in use as shown below:
Immediately after being started,
msserver begins to broadcast its position (IP and PORT - see msserver.cpp
ServerBroadcastThread function). Notice how message-packet sending is done when using mailslots:
WriteFile functions are used.
CreateFile opens, in this case, not a file but a mailslot name \\\\*\\mailslot\\@_MSClient_@. Notice the name convention: * means all computers which are reading a mailslot named \\\\.\\mailslot\\@_MSClient_@. Then,
client instances over the network open and read mailslots with that name.
If you want, you might use a sniffer to check what the
server is broadcasting.
client), you will see the following:
client instance creates a mailslot named \\\\.\\mailslot\\@_MSClient_@ and starts reading it (in fact, you can have one process using that name each time - see the msclient.cpp to see how to handle that). After it gets the
server message-packet, it configures a
stream socket connection and starts a kind of "PING" with the
CreateMailslot is the function used to create a mailslot and
ReadFile to read from it.
You can have more than one
client per machine.
Server is a multi-thread application and it can handle many
clients at a time.
|Writing to a Mailslot|
|Reading from a Mailslot|
Enjoy. Hope this helps.