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

Creating a Network Streaming Server

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

namespace NetworkIOServer
{
    public class NetworkIOServer
    {
        public static void Main(string[] args)
        {
            NetworkIOServer app = new NetworkIOServer();
            app.Run();
        }

        public void Run()
        {
            IPAddress localAddress = IPAddress.Parse("127.0.0.1");
            if (localAddress == null)
                return;

            TcpListener tcpListener = new TcpListener(localAddress, 65000);
            tcpListener.Start();

            while (true)
            {
                Socket socketForClient = tcpListener.AcceptSocket();
                Console.WriteLine("Client is connected.");

                SendFileToClient(socketForClient);

                Console.WriteLine("Disconnecting from client...");

                socketForClient.Close();
                Console.WriteLine("Program is being closed...");
                break;
            }
        }

        public void SendFileToClient(Socket socketForClient)
        {

            using (NetworkStream networkStream = new NetworkStream(socketForClient))
            {
                using (StreamWriter streamWriter = new StreamWriter(networkStream))
                {
                    using (StreamReader streamReader = new StreamReader(@"C:\test\myTestFile.txt"))
                    {
                        string text;

                        do
                        {
                            text = streamReader.ReadLine();

                            if (text != null)
                            {
                                Console.WriteLine("Sending {0}", text);
                                streamWriter.WriteLine(text);
                                streamWriter.Flush();
                            }
                        } while (text != null);
                    }
                }
            }
        }
    }
}
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