Acts as a server program to demonstrate the use of the NetworkStream class : NetworkStream « Network « C# / C Sharp






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

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);
        }
    }
}


           
       








Related examples in the same category

1.Write to a NetworkStream
2.implements a NetworkStream server
3.implements a NetworkStream client 2
4.Acts as a client program to demonstrate the use of the NetworkStream classActs as a client program to demonstrate the use of the NetworkStream class