Streamsocket example c# metro
Posted on April 7, 2012
A socket provides send and receive over TCP and a StreamSocketListener will listen for incoming TCP connections.
The sample will act as a server or client depending on which buttons you press, i.e. press listen to be a server and connect to be a client. Also, you can set the same program as client and server ad have it communicate with itself.
To start the listener wire up a connection received event handler and bind the service name…
The event handler stores the incoming socket in a list (so it can use it to reply), and waits for incoming data from it. The ‘waiting for incoming data’ bit looks like this…
It uses a DataReader to read from the incoming socket and then calls itself to wait for subsequent incoming message data.
Note that the samples use a protocol which sends the length (number of bytes) of the message first followed by the message data itself. If you want to use a different strategy, for example characters to delimit the start and end of a message then the code will change a little bit. The difference being that you won’t always know how much data to read. You can modify the code like this to accommodate this:
Note that setting the InputStreamOptions to Partial will allow you to specify a larger buffer but also the async load operation will complete when a smaller sized buffer comes in. This enables you to read the data coming in and respond to it accordingly.
The pictures show a session between a socket server running on a build slate and a win8 vm both on my local network..
The project can be downloaded from here.
UPDATE: This project has been updated for the Release Preview