A Small TCP Experiment

I’m going to be writing some networking code for a personal project, so I spent some time learning to use TcpClient/TcpListener. After starting to learn them, I thought it might be interesting if I could send a delegate across the wire.

Since I wasn’t quite sure what I’d be sending and receiving when I started learning how to use the TcpClient class, I decided that I would use BinaryFormatter to serialize all of my messages. This meant that I could easily create a class that contained everything I wanted to send. This is where I started my experiment:

[Serializable]
public class InfoToSend
{
    public string Message
    { get; set; }
 
    public delegate void MessageParse(string text);
    public MessageParse MessageParsingMethod
    { get; set; }
}

In my first attempt, I set MessageParsingMethod to a method that was in the WinForm I am using as a GUI for the project. This threw an exception that came from an unintended consequence of trying to serialize a delegate: it also tried to serialize my form, which isn’t serializable.

To get around this limitation, I created a new class that didn’t do exactly what I wanted, but allowed me to demonstrate sending a delegate:

[Serializable]
public class ShowMessageBox
{
    public void YesNo(string message)
    { MessageBox.Show(message, "", MessageBoxButtons.YesNo); }
 
    public void Ok(string message)
    { MessageBox.Show(message); }
}

Setting the MessageParsingMethod in InfoToSend to one of these two methods worked like a charm. The message was sent, and the proper method was called in the receiving instance of the program.

While my experiment worked, it has quite a large limitation: the class that contains any method I want to call must be serializable, and the serialized data of that class will be sent across the wire. This could seriously bloat the amount of data being sent.

My next step is to clone my learning project in WCF to figure out the differences between the two and the merits of each.

This entry was posted in .Net, C#, Networking. Bookmark the permalink.