Network Streaming Server : NetworkStream « Network « C# / CSharp Tutorial






using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

   public class NetworkIOServer
   {
      public static void Main()
      {
         IPAddress localAddr = IPAddress.Parse( "127.0.0.1" );
         TcpListener tcpListener = new TcpListener( localAddr, 65000 );
         tcpListener.Start();

         for ( ; ; )
         {
            Socket socketForClient = tcpListener.AcceptSocket();
            SendFileToClient( socketForClient );
            socketForClient.Close();
            break;
         }
      }

      static void SendFileToClient(Socket socketForClient )
      {
         NetworkStream networkStream = new NetworkStream( socketForClient );
         System.IO.StreamWriter streamWriter = new System.IO.StreamWriter( networkStream );
         System.IO.StreamReader streamReader = new System.IO.StreamReader("myTest.txt" );
         string theString;
         do
         {
            theString = streamReader.ReadLine();
            if ( theString != null )
            {
               Console.WriteLine("Sending {0}", theString );
               streamWriter.WriteLine( theString );
               streamWriter.Flush();
            }
         }
         while ( theString != null );
         streamReader.Close();
         networkStream.Close();
         streamWriter.Close();
      }
   }








33.16.NetworkStream
33.16.1.Create a NetworkStream from a Socket
33.16.2.NetworkStream TcpClient
33.16.3.Use NetworkStream to read and write to a server
33.16.4.Tcp client: Use StreamReader and StreamWriter to read and write to a server
33.16.5.Network Streaming Client
33.16.6.Network Streaming Server