Sunday, June 17, 2007

Homebrew C# Mailslot Control

To download the actual project, visit the CodeProject page.

Introduction

For a recent project I needed to create a local LAN chat application that was secure and connectionless. From prior projects I know a simple way to accomplish this is using Windows Mailslots. Unfortunately, .NET does not have built-in support for using them and one is forced to P/Invoke API calls directly. After searching many newsgroups and sites such as CP, I found some suggestions and random P/Invoke signatures but nothing usable so I had to create it from scratch. And now I offer my findings to you.

One important thing to note is that this project will throw an exception if run from the debugger. This is because the OnReceivedData event is fired from a different thread than the UI is running in. There are easy ways around this using TextBox.InvokeRequired which you will find if you search, however this article does not go into that issue.


Background

If you're new to programming, you probably aren't familiar with what a Mailslot is. In simplest terms, a "slot" is a virtual file. In order to pass data between two points, two things must happen at each point. Both ends must open the slot in read mode locally, and in write mode remotely. Remember we are treating the slot as a file. Client A writes a message to the slot \\ClientB\Slotname and Client B reads it from \\.\Slotname. Alternatively, if the remote slot is opened as \\*\Slotname, then the message will be sent to Slotname on all computers on the local domain or workgroup. If a computer receives a message to a slot that it does not have opened, Windows will ignore it by design.

Mailslot communication is done over UDP port 137. The useful thing about this method, is that it requires no actual connection to be established, and no central server is required.

For the rest of the article and source code, visit the link above.


Labels: , ,