Acts as a server program to demonstrate the use of the NetworkStream class : NetworkStream : Network C# Source Code


Custom Search

C# Source Code » Network » NetworkStream »

 

Acts as a server program to demonstrate the use of the NetworkStream class









    

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// NStrSvr.cs -- Acts as a server program to demonstrate the use of
//               the NetworkStream class.
//
//               Compile this program with the following command line.
//                   C:>csc NStrSvr.cs
//
// To use this program with the companion client program, first start
// the server (this program), then connect to it using the client program
// in a separate console window.
// As you enter lines from the client, they will appear in the server
// console window. To end the session, press <Enter> on a blank line.
//
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace nsStreams
{
    public class NStrSvr
    {
        static public void Main ()
        {
            IPAddress hostadd = Dns.Resolve("localhost").AddressList[0];
            Console.WriteLine ("Host is " + hostadd.ToString());
            IPEndPoint EPhost = new IPEndPoint(hostadd, 2048);

            Socket s = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream,
                                  ProtocolType.Tcp );
            s.Bind (EPhost);
            s.Listen (0);
            Socket sock = s.Accept();
            NetworkStream strm = new NetworkStream (sock, FileAccess.ReadWrite);
            byte [] b = new byte [256];
            while (true)
            {
                for (int x = 0; x < b.Length; ++x)
                    b[x] = 0;
                strm.Read (b, 0, b.Length);
                if (b[0] == 4)
                    break;
                string str = ByteToString (b, 0);
                Console.WriteLine (str);
            }
            strm.Close ();
            sock.Close ();
            s.Close ();
        }

        // Convert a buffer of type byte to a string
        static string ByteToString (byte [] b, int start)
        {
            string str = "";
            for (int x = start; x < b.Length; ++x)
            {
                if (b[x] == 0)
                    break;
                str += (char) b [x];
            }
            return (str);
        }
    }
}


           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Network
» NetworkStream