Reading and Writing Data – C# – part 6 (Network I/O)

Creating a Streaming Network Client

using System;
using System.IO;
using System.Net.Sockets;

namespace NetworkStreamingClient
{
    public class Client
    {
        static void Main(string[] args)
        {
            TcpClient socketForServer;
            try
            {
                socketForServer = new TcpClient("localHost", 65000);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to connect to server at {0}:65000", "localhost");
                return;
            }

            NetworkStream networkStream = socketForServer.GetStream();
            StreamReader streamReader = new StreamReader(networkStream);

            try
            {
                string outputString;

                do
                {
                    outputString = streamReader.ReadLine();

                    if (outputString != null)
                    {
                        Console.WriteLine(outputString);
                    }
                } while (outputString != null);
            }
            catch (Exception)
            {
                Console.WriteLine("Exception reading from Server");
            }
            finally
            {
                networkStream.Close();
            }
        }
    }
}
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