Skip to main content

TCP servers with .NET: Scenario 2 - Optimistic Blocking Servers

This post is part of a series, to see the other posts in the series go to the series index.

imageIn the previous post we looked at the simplest of all TCP server scenarios, but what about the third issue highlighted in the post: It assumes your clients will connect, pass data and disconnect. What about for clients the connect optimistically so that they can send data at some point in the future?

This is very common for games, where the client connection process is very slow or where even smallest of overhead should be eliminated.

In this mode rather than read data and disconnect we add a loop on the reading and read until we get a end of message notice and will then end the connection.

The problem with extending the simple model to this, is that we now have a blocking action, i.e. code can not continue until something happens, in both the server thread and in all the client connection threads. So now shutting down the server is not just related to the server, we need clients to disconnect properly first.

What is common here, is to send a message to all clients saying it will shutdown and then having them do that. That assumes we have pretty smart clients and/or control them and in scenarios you do not control the TCP clients it could be a bit problem. We will look at a way to solve this in the next post, but for now the code below shows how this is done, and compared to scenario 1 it contains one small change:

class Program
{
    private const int BufferSize = 4096;
    private static bool ServerRunning = true;

    static void Main(string[] args)
    {
        new Thread(RunTCPServer).Start();
        Console.WriteLine("Press enter to shutdown");
        Console.ReadLine();
        ServerRunning = false;
    }

    private static void RunTCPServer()
    {
        var tcpServer = new TcpListener(IPAddress.Any, 9000);
        try
        {
            tcpServer.Start();
            while (ServerRunning)
            {
                var tcpClientConnection = tcpServer.AcceptTcpClient();
                Console.WriteLine("Client connection");

                // spawn thread to deal with it     
                new Thread(ClientConnection).Start(tcpClientConnection);
            }
        }
        finally
        {
            tcpServer.Stop();
        }
    }

    private static void ClientConnection(object state)
    {
        var tcpClientConnection = state as TcpClient;
        var stream = tcpClientConnection.GetStream();
        var buffer = new byte[BufferSize];
        while (ServerRunning)  // new in scenario 2
        {
            var amountRead = stream.Read(buffer, 0, BufferSize);
            var message = Encoding.ASCII.GetString(buffer, 0, amountRead);
            Console.WriteLine("Client sent: {0}", message);
        }
    }
}

TCP servers with .NET: Scenario 1 - Simple TCP servers

This post is part of a series, to see the other posts in the series go to the series index.

imageWriting a TCP server is something that modern business .NET developers do not need to worry about, we have WCF which has abstracted us from understanding TCP servers & clients for business apps – but for some systems we still need to write a TCP server or client.

Microsoft has optimised the .NET framework for common scenarios – for example doing something like SMTP where a server where it is always running and clients connect when they have data, provide the data and disconnect. So what you may do is start a server (in it’s own thread so you can still do other things in the app), and wait for client connections. At this point you are blocking processing until a client connects. When a client connects, you get the data and process it (in a new thread, so you can allow more clients to connect).

The advantage of this is this is a simple model and is fairly easy to setup, but there is a few problems with this:

  1. You have this blocking point while you wait for clients, so trying to shut it down is difficult. As the view of a server is that it should always be up, this is not an optimised path so there is no way. Basically you will need to deal with task manager to kill the process.
  2. You have lots of threading and you must handle threads. Threads are hard to understand and easy to fail so we are opening up potential for problems.
  3. You assume the client will connect and send data at once and will go away. Once again this is the “normal” scenario (think HTTP or SMTP) but there are scenarios where this is not possible.

Below is the sample to do this in a console application.

class Program
{
    private const int BufferSize = 4096;
    private static bool ServerRunning = true;

    static void Main(string[] args)
    {
        new Thread(RunTCPServer).Start();
        Console.WriteLine("Press enter to shutdown");
        Console.ReadLine();
        ServerRunning = false;
    }

    private static void RunTCPServer()
    {
        var tcpServer = new TcpListener(IPAddress.Any, 9000);
        try
        {
            tcpServer.Start();
            while (ServerRunning)
            {
                var tcpClientConnection = tcpServer.AcceptTcpClient();
                Console.WriteLine("Client connection");

                // spawn thread to deal with it     
                new Thread(ClientConnection).Start(tcpClientConnection);
            }
        }
        finally
        {
            tcpServer.Stop();
        }
    }

    private static void ClientConnection(object state)
    {
        var tcpClientConnection = state as TcpClient;
        var stream = tcpClientConnection.GetStream();
        var buffer = new byte[BufferSize];

        var amountRead = stream.Read(buffer, 0, BufferSize);
        var message = Encoding.ASCII.GetString(buffer, 0, amountRead);
        Console.WriteLine("Client sent: {0}", message);
    }
}

Windows Phone 7 Apps: SA ID Number Tools & AA Rates Calculator Updates

I have a few Windows Phone 7 apps, and two of those are the SA ID Number Tools and the AA Rates Calculator ones. You may be familiar with the AA Rates one from my friend, Rudi Grobler, who used it in his TechEd talks to show a UI that did not follow the model correctly Disappointed smile

I took this and the Windows Phone UX training I attended to heart and put a lot of work into updating them and making them a lot more in line with the WP7 UI guidelines.

AA Rates Calculator

The first think is this application has dropped the yellow background, which made sense for an AA tool (being their colour is yellow), and now is black or white depending on your theme. All controls have been updated to reflect that too. I have also fixed the alignment things Rudi was so quick to point out.

I use the highlight colour now and larger typography to really make the key information stand out from the rest – this is something I learnt at the UX camp.

In addition I have some other new features:

  • About to share your rate via email or social networks (twitter, facebook etc…)
  • The yellow branding is used in a position bar to give you an idea of how much is in the app.
  • I also added a fuel price page so you can always have the latest fuel price information!
  • The information pickers have also had an update and the selection is much larger now, so easier for people with big hands like me.
  • Fuel price can be displayed on a live tile too!

aa-1.3_10-27-2011_11.37.29.695aa-1.3_10-27-2011_11.37.33.281aa-1.3_10-27-2011_11.37.37.515

SA ID Number Tools

Once again I dropped the background green (which was a photo of my ID book cover) and that also meant being able to move to a pivot control rather than a (heavy) panorama control. The green/gold theme has been mostly lost, with gold being used in selective places in the application. Also a careful use of font sizes and colours in the application to make the information stand out more.

aa-1.3_10-27-2011_18.26.34.627aa-1.3_10-27-2011_18.26.39.767aa-1.3_10-27-2011_18.26.45.727

Hopefully these changes make these apps feel faster, easier to use and more part of your phone than before!

Windows Phone 7: Professional Tips - Press and hold

RobertThe keyboard on WP7 is an amazing area which you will be often exposed to, so it is not surprising it contains some hidden gems to make the experience better, like double tap.

Today the hidden gem is the ability to press and hold keys to get pop ups with other options, which could save you navigating to the symbols/number section or even give you access to options that you never had anywhere else.

If you have a look at the screen shot you will see the dot key has been pressed and held and the popup has dash, exclamation, colon, question mark and dot in it. Much easier to find than going to the symbols section.

Other keys with this. Letters shown in lower case support this on upper case too:

  • e – ê è ë é
  • t – þ
  • y – ý ÿ
  • u – ù ú û ü
  • i – ì í î ï
  • o – ò ó ô ö ø œ
  • a – ä á â à å æ
  • s – ß §
  • d – ð
  • c – ç ©
  • n – ñ
  • m – ɥ
  • 1 – ⅓ ¼ ½
  • 2 – ² ⅔
  • 3 – ¾ ³
  • 0 – °
  • £ – $ ¢ € ¥ ¤
  • ( – < { [
  • ) – > } ]
  • - - _ ~ ¬ ·
  • ! – ¡
  • ' – ´ `
  • " – « » “ ”
  • ? - ¿

Windows Phone 7: Professional Tips & Dismiss notifications

source http://www.windowsphoneitaly.com/news/eventi/3123-mix11-windows-phone-7-con-larrivo-di-mango-sara-revisionato-il-sistema-delle-live-tiles.htmlWindows Phone 7 supports little pop up notifications, which are called toasts (cause they pop up like bread in a toaster). You will see these when you get a text message (SMS) or from games (like Tanks) or in chat programs like WhatsApp.

These can linger around for a little bit, but you can get rid of them quickly – just swipe across them, like you were flicking them away and they will rush off your screen.

I use this a lot with WhatsApp when I get multiple messages quickly so I can clear the first and see the second toast which is under it or when I am playing a game and I want to get that SMS off screen so I can continue to play.

It’s another example of the UX in the phone having great little touches.

The Arturo Grid for Windows Phone 7 in PNG & GIMP

layoutArturo Toledo works at Microsoft on the Windows Phone Design Studio team, and last week I had the chance to attend phone training with him. In that training he showed a grid he used for layout so that his apps match the layout of Windows Phone 7 apps – I call this the Arturo Grid.

Yesterday he posted about it and released an Expression Design version of it, which is great if you have Expression Design… but if you don’t it can be a problem. So I recreated it using the free graphics tool, The GIMP, and produced a transparent PNG version so that it can work in just about anything!

Downloads

How I did it?

GIMP is a fantastic tool and I thought I would share how I created this layout. First I started with a new image, with the resolution of 480 x 800 and a transparent background.

image

Next run FiltersRenderPatternGrid and set the parameters as in the screen shot below. Note the offset horizontal & vertical lines are not linked. What we are doing here are creating grids of 37x37 (25 + 12 based off the Arturo Grid) with line width of 12 (so the space that is left is 25x25). The offset is +6 so that it pushes out, because the line widths are based on the middle of the line and not the edge.

image

Now add two layers, another transparent one and a white backed layer.

image

Place the new transparent at the bottom and the white in second place.

image

and now merge down the grid layer onto the white layer.

image

Now drag on guides:

  • Vertical: 24px
  • Vertical: 456px
  • Horizontal: 56px
  • Horizontal: 784px

and select that region.

image

Create a new

Then use Select ► Invert and press delete. This removes the area around the grid for the bleed (padding) area that your app shouldn’t use.

image

Now use the Fuzzy Select Tool (aka the magic wand selector tool) and click on the black.

image

Now hit delete to remove those black lines leaving just the white squares.

image

You can tweak the colours using the colour exchange tool (Colors ► Map Color ► Exchange) and you can tweak the transparency using the Opacity option on the layer tool to make it more transparent.

image

There you go, now you are done Smile

image

File attachments
layout.png (2.62 KB)
wp7grid.xcf (465.82 KB)

Windows Phone 7: Professional Tips - Double tap

D04When you want to make sure something is dead (finished), you shoot it twice – also known as a double tap. Windows Phone 7 supports this too… for sentences.

When typing, double tap the space key and it will insert a full stop and a space!

Considering the size of the space key and how easy it is to double tap, rather than find the smaller dot key and move to the space key it can save you a little.

This is just one of the many awesome UX features in the phone!

Tech·Ed Africa: Slides, Scripts & Thoughts

WP_000405WOW! I am sitting here under s a fake tree in a fake city that is Micropolis (also known as the Tech·Ed Africa 2011 expo, and it is AMAZING!). I have just finished my third and final presentation at Tech·Ed Africa 2011 and I just wanted to say THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU to all the people who attended my talks!

This year not only has an amazing expo, but the audiences have been by far the BEST EVER! A special thanks to those who braved 8am to see my .NET 4 talk – 2min before I started I thought “I need sleep”, 2min after the energy from the audience was flowing and I never looked back at what I felt was a great talk, so thank you! Smile

what it looks like from the presenter at #techedafricaA special work of thanks to Suliman and DPE (it is their fake tree I am sitting under) for arranging this and the opportunity to present! I also want to say thanks to the technical team at the event, without who you would not see or hear me, and they were fantastic this year!

For those who attended my talks, or those who couldn’t below are the slides, scripts and misc files used in the talks!

(for those in an RSS reader or on the home page, click read more)



Power features in .NET 4: Investigating the features of .NET 4 which you don’t know about

File downloads

Extend Visual Studio 2010

File downloads

Building Business Applications with Microsoft Visual Studio LightSwitch

File downloads

Tech·Ed Africa 2011 for Windows Phone 7 - 1.1 released

Update: This application has been retired - it was for TechEd 2011 and used the website a lot, the moment the site changes the app will break. It's goal & use are done, so I am happy to retire it.

iconI’m very happy to announce the 1.1 version of the Tech·Ed Africa app for Windows Phone 7 is now out with a TON of new features:

First up is dedicated in app pages for speakers. This means no more browsing to the website for speaker info. There is also options to view their Twitter, website etc… and since we not on Mango it supports saving the contact details to the device.

teched-1.2_10-6-2011_16.9.27.591

Second  is similar, dedicated pages for the sessions too!

teched-1.2_10-6-2011_16.7.47.75

Third improvement is on the sessions list page – a lot of cleanup and bug fixing there plus lots of options for the grouping (level, audience etc..). This should help finding session info very easily.

teched-1.2_10-6-2011_16.7.31.361

The MVP page got a BIG facelift too, with buttons for contact details for each MVP, and a cleaner more bold experience. Of the whole application I am most happy with the UI on this page. I also added a community tweets page that has tweets searched by hash tags!

teched-1.2_10-6-2011_16.9.41.901

The welcome page got a cleanup with more focus on the news tweets and the removal of the refresh option, since it refreshes in a lot of ways manual isn’t really needed. It also allows you to launch the BIG new feature…

teched-1.2_10-6-2011_16.7.22.575

Session planner! You can now browse and book sessions on your phone! And your phone will give you reminders to attend the sessions!

teched-1.2_10-6-2011_16.9.55.431

There is also a lot of UI tweaks – first the background was swopped to the latest UI from Tech·Ed and made a lot darker, so the contrast to the white stands out more the readability is WAY better. I also spent a lot of time with Rudi Grobler getting some of the smaller UI things right, so a big thanks to him! It even has a new and MUCH nicer icon Smile So what are you waiting for, go update NOW!

wp7_278x92_blue