Software Engineering, a personal journey

Socket, Streams and Texas Hold'em

Got handed a great head scratcher at work recently, as an aside from the general day-to-day office stuff, we have technical challenges too

Bob the lead Developer set everyone the challenge to create a simple app which communicated with a remote server. The purpose was to get everyone up to speed with sockets and threads in C#. As the challenge was part of a final solution (the creation of a Texas Hold'em bot) this first step is pretty basic. My solution is below but it's only an initial one. There's no error correction or threading and I want it to work in a WinForm app (so I can add a lovely GUI). I've used TcpClient instead of resorting to the lower level Socket just to make thing easier for myself. TcpClient is used to create a connection and then a NetWorkStream is used to read and write to and from the client-server.
using System;
using System.Net.Sockets;
using System.Text;

internal class ClientSocket
    private static void Main(string[] args)
        bool returnedCall = false;// use a boolean to confirm client send
            var tcpClient = new TcpClient("", 8000);// define a socket
            var networkStream = tcpClient.GetStream();// define a stream to read n write
            while (true) //keep requesting server ping
                if (!returnedCall)// only perform client send once
                    var outStream = Encoding.UTF8.GetBytes(Console.ReadLine());//encode user input as UTF-8
                    networkStream.Write(outStream, 0, outStream.Length);// stream the input to the server
                    networkStream.Flush();// empty the stream

                var inStream = new byte[512];//define a variable to hold server response
                networkStream.Read(inStream, 0, 512);// read from stream the server response
                var returndata = Encoding.UTF8.GetString(inStream);// encode response as UTF-8
                Console.WriteLine("Reply from Server: " + returndata);// Console out the server response
                returnedCall = true;// only loop once for the client input but repeat for the server
        catch (SocketException ex)
            Console.WriteLine(ex);// what when wrong


Have your say


Comment here (140 chars only)*:

Email address: