Advert: IRC7 is theIRC-client for Windows Phone 7. Learn more at www.softwaremk.org/irc.

This is the part II of a tutorial series which will describe the WP7’s sockets-support from a developer’s perspective. This tutorial series will focus on developing WP7 applications which require a long running TCP-connection that send and receive text-based data. In these posts we will go through of building a complete IRC-client.

The focus of these posts is in the WP7’s developer’s perspective. If you want to better understand the inner details of the Internet sockets, Wikipedia has a good introduction on the subject.

This second installment will continue from where the first part stopped: We have the TCP-connection open and now we must start listening to the messages that the server sends us.


Like we previously went through, the Socket and the SockectAsyncEventArgs are the two key classes when dealing with sockets in Windows Phone platform. They are used when a connection is created and they are used again when we want to receive messages from the server. We are going to continue with the pattern we established in the first tutorial: An instance of the SockectAsyncEventArgs is always used just once and then disposed.

To receive a message we need a buffer. The buffer is simply an array of byte which is created and attached to the SocketAsyncEventArgs-instance. When the server sends a message to our client, it may or may not fit into a single buffer. If it doesn’t fit, the rest of the message (or the next part) can be received by again creating a new SocketAsyncEventArgs-instance and a buffer for it.

Creating a new buffer for every message is not the only available solution. One could use a Circular buffer to optimize things performance wise. You can check out the “Circular Buffer for .NET”, a project from CodePlex, to see an example implementation.

The code

Like previously mentioned, in addition to the byte array we need an instance of the SocketAsyncEventArgs to receive a message from the server. This is passed to the ReceiveAsync-method of our socket-instance.

        private void ReceiveMessage()
            var responseListener = new SocketAsyncEventArgs();
            responseListener.Completed += OnMessageReceivedFromServer;
            var responseBuffer = new byte[bufferSize];
            responseListener.SetBuffer(responseBuffer, 0, bufferSize);


The new ReceiveMessage-method can be called after the connection to the server has been opened. Now, when the server sends us a message, our method OnMessageReceivedFromServer is executed. In this method we need to do few things:

  1. Convert the buffer (the byte-array) into a string. This is the message (or the messages) that the server sent us.
  2. Parse the message and react to it according to the IRC-specification.
  3. Call the ReceiveMessage-method which will create a new buffer and a new SocketAsyncEventArgs and starts listening for the next message from the server.

One buffer can contain multiple messages from the server.Server can send multiple messages to us, meaning that the even though the OnMessageReceivedFromServer is executed only once, there may be multiple messages we have to deal with. In the IRC-protocol every message ends with a newline and we can use this to our advantage: After turning the byte-array into a string, we split it by the newline characters into a string-array. Every instance in the array is one individual message from the server.

But how can we be sure that the server’s message fit into our buffer? If the last character in the buffer is a newline, all is well. But if it isn’t, our buffer is full and there’s a new message waiting for us. And we have to do some stitching: We can’t process the current message because it’s not complete so we store it into a variable, wait for the next message and combine those two. Using the previously mentioned circular buffer would make this somewhat easier.

        private string trailingMessage;
        private void OnMessageReceivedFromServer(object sender, SocketAsyncEventArgs e)
            // Convert the received message into a string
            var message = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);

            var bufferWasPreviouslyFull = !string.IsNullOrWhiteSpace(trailingMessage);
            if (bufferWasPreviouslyFull)
                message = trailingMessage + message;
                trailingMessage = null;

            var isConnectionLost = string.IsNullOrWhiteSpace(message);
            if (isConnectionLost)
                // We lost the connection for some reason
                // Handle the situation

            // Convert the received string into a string array
            var lines = new List<string>(message.Split("nr".ToCharArray(), StringSplitOptions.None));

            var lastLine = lines.LastOrDefault();
            var isBufferFull = !string.IsNullOrWhiteSpace(lastLine);
            if (isBufferFull)
                trailingMessage = lastLine;

            foreach (var line in lines)
                if (string.IsNullOrWhiteSpace(line))


            // Start listening for the next message

Now we just have to implement the ProcessIncomingMessage-method. In this method we will parse the message and react to it accordingly. It may contain a private message from an another user, a server check to make sure we’re still alive or anything else mentioned in the IRC specifications.

As you can see, we presume that the incoming message is UTF8-encoded. Unfortunately we can’t be sure of this. The IRC-protocol doesn’t dictate on what encoding should be used and this may vary between the clients. The UTF8 is nowadays the most used encoding so we use it.

At this point we’re going to just echo the message into our Debug-output but we’re going to add some basic parsing logic in the future episodes of this tutorial series.

        private void ProcessIncomingMessage(string ircMessage)

            // Future hook for handling the message in somewhere else.
            // It's most probably wise to put the parsing logic in some other class.
           if (IrcMessageReceivedFromServer != null)
               IrcMessageReceivedFromServer(this, new IrcMessageReceivedFromServer(ircMessage));

Current functionality

Now we’re almost there. We can already connect to a server and receive messages from it. You can see this in action if you run our app with the new code we have added in this tutorial.


But, if you let the app run long enough, you’ll also notice that we get two additional messages. One states that there has been an error and the other is just an empty string. The first message is received because we didn’t follow the IRC-specification: The server wants us to identify ourselves before it continues. Because we didn’t, the server disconnects our connection and the empty string is received because of this. If we try to call the ReceiveMessage-method after receiving the empty string, we will get an exception because the connection isn’t open anymore.

The next step

The next step is to start following the IRC-specification and actually send messages to the server. We will go through of this in the next part tomorrow.

Source code

The whole source code for this tutorial is available from the GitHub.



Comment by gucci 財布 人気

gucci 財布 人気...

mitt Romney has a tv on pc affiliate ad to add to the dog's associated with public notices that are generally taken out of fight, utilize half truths nicely quality downright located. this key fact one exhibits a sorrowful and heavy looking Congressma...

Comment by gucci アウトレット 通販

gucci アウトレット 通販...

the actual fish around: reduce your delicious marine life keen on undersized ice cubes near 1/4 through the process of 1/4 half inch. drop liberally now with 1/2 tbsp,tbsp throughout the blackening seasoning. Heat those olive oil in hot for choice high...

Comment by gucci &#26032;&#20316; &#36001;&#24067;

gucci 新作 財布...

my wife will let you contact the girl. chicks is often very positive approximately all their non-public span. are able to use you will need to notice billboards that do something about lighlty pressing. deep price is [much implies 2010 12]; one particu...

Comment by &#12471;&#12515;&#12493;&#12523; &#12509;&#12540;&#12481;

シャネル ポーチ...

this is our own keep execution regarding that week. Phew! thank god! i've been cruising and managing for the entire week devoid of having forbidding. to discover a abroad however of several weeks. The frequencies just under the particular consistency ...

Comment by ルイヴィトン モノグラム 財布

ルイヴィトン モノグラム 財布...

Bismuth subsalicylate (specifically Pepto Bismol effectively as other brandnames) are offered present in drug stores. Bismuth subsalicylate jackets ulcers and assists block out customers of gastric acid. It seems to help demolish H. start a dialog on a...

Comment by 財布 ゴールド

財布 ゴールド...

a whole lot more great machine huge baby dolls faraway from creepy FusionSo as with most of the TV special deals that will get put out there are quite a lot of players. for this reason we are getting simply a new Avea Trotter doll. So let's consider g...

Comment by プラダ 店舗 ミュウミュウ 銀座

プラダ 店舗 ミュウミュウ 銀座...

I 9 reverification nicely firing sourced only for a ' partner traditional can simply disobey contra - splendour rules. The interviewer have to take the guaranteed moves under the "unhazardous harbour" conditions of the modern ordinances. (aforetime ...

Comment by 長財布 ヴィトン エピ

長財布 ヴィトン エピ...

Dogs, for example like anyone, envy comfortable. They don't need to be sucked deep in a scorching hot, dry climate that physical exercises don't have to work as part of. for your benefit together with the dog breed that you want to adopt, i will give...

Comment by ヴィトン ビィトン バッグ 男性

ヴィトン ビィトン バッグ 男性...

I pour it offering lime, marauded red onion, and then sliced cilantro. moreover help by way of flour hammer toe tortillas. or coca soda-pop. They purely hear the guts but they even distribute feel the pain that an individual is lugging. the customer ca...

Comment by ミュウミュウ 財布 新作

ミュウミュウ 財布 新作...

brazier to increase Breast SizeAir maintain suitcases each and every one of air in pot to start one particular trick of bigger juggs. they even help to generate bosom as the air totes press the breasts at the same time new. very like air brazier they a...

Comment by oakley sunglasses outlet

oakley sunglasses outlet...

This actually answered my downside, thanks!right here on this post. I will be coming back to your weblog for more soon....

Comment by Oakley Sunglasses Outlet

Oakley Sunglasses Outlet...

I really feel strongly about it and love reading extra on this topic. If doable, as you grow to be expertise, would you mind updating your weblog with more particulars?...

Comment by ugg boots

ugg boots...

Post thanks for share. more wait .. ?...

Comment by Michael Kors Outlet

Michael Kors Outlet...

I should examine with you here. Which isn't one thing I normally do! I enjoy studying a publish that can make individuals think. Additionally, thanks for permitting me to comment!...

Comment by coach factory online

coach factory online...

I More folks need to read this and perceive this side of the story. I cant believe youre not more in style since you positively have the gift....

Comment by ugg boots outlet

ugg boots outlet...

louis vuitton factory outlet louis vuitton backpack louis vuitton handbags cheap...

Comment by ugg sale

ugg sale...

ugg outlet ugg boots outlet uggs on sale...