Send inkCanvas content with TCP

An inkcanvas can be serialized so that you have a byte array to send over a network.

For the client, in this case the canvas someone draws on, you create a TcpClient.

Fortunately this is handled by the .Net framework for you.

TcpClient client = new TcpClient(“192.168.0.1”, 42000);

Next you create a MemoryStream to save your StrokeCollection on the inkCanvas to. The Networkstream doesn’t support this. But you can send the byte array without problems.

MemoryStream memstream = new MemoryStream();

Get the Networkstream form the TcpClient.

NetworkStream netstream = client.GetStream();

In a real application you should put this in a separate thread, but for this example let us simply assume this is running in the Window with the inkCanvas. This saves the inkCanvas Stroke Collection to the memory as a byte array.

this.inkCanvas1.Strokes.Save(memstream);

The byte array can be send to the networkstream and with that to the TcpServer on the other end of the connection.

netstream.Write(memstream.GetBuffer(), 0, memstream.GetBuffer().Length);

Some cleaning up and the client is complete.

memstream.Close();

netstream.Close();

client.Close();

Please note that you need to at least catch some exceptions before using this in any real application.   #

 

The server looks pretty much the same.

Create the Server in the form of a TcpListener. The framework handles this for you.

TcpListener server = new TcpListener(42000);

Start the server. server.Start();

Tell the server to Accept a waiting connection from a TcpClient and save this client. This will freeze the Thread till a connection is established. So better put this in some other thread that is dedicated to communication.

TcpClient client = server.AcceptTcpClient();

Grab the Networkstream the client is writing to.

NetworkStream netstream = client.GetStream();

Fortunately the StrokeCollection Class has a constructor that take a stream as parameter. StrokeCollection p = new StrokeCollection(netstream) ;

The usual cleanup.

netstream.Close();

client.Close();

server.Stop();

And don’t forget to pass the information somewhere. If you are sure, that nothing will happen with the object you can save the Clone(). But it is more secure to make a copy of the data for the gui. Otherwise you might get into troubles with the next update.

this.inkCanvas1.Strokes = p.Clone();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: