Asynch Network Server : TcpListener « Network « C# / CSharp Tutorial






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

        class ClientHandler
        {
            private byte[] buffer = new byte[256];
            private Socket socket;
            private NetworkStream networkStream;
            private AsyncCallback callbackRead;
            private AsyncCallback callbackWrite;

            public ClientHandler(Socket socketForClient)
            {
                socket = socketForClient;
                networkStream = new NetworkStream(socketForClient);
                callbackRead = new AsyncCallback(this.OnReadComplete);
                callbackWrite = new AsyncCallback(this.OnWriteComplete);
            }
            public void StartRead()
            {
                networkStream.BeginRead(buffer, 0, buffer.Length,callbackRead, null);
            }
            private void OnReadComplete(IAsyncResult ar)
            {
                int bytesRead = networkStream.EndRead(ar);

                if (bytesRead > 0)
                {
                    string s = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    Console.Write(s);
                    networkStream.BeginWrite(buffer, 0, bytesRead, callbackWrite, null);
                }
                else
                {
                    networkStream.Close();
                    socket.Close();
                    networkStream = null;
                    socket = null;
                }
            }
            private void OnWriteComplete(IAsyncResult ar)
            {
                networkStream.EndWrite(ar);
                networkStream.BeginRead(buffer, 0, buffer.Length,callbackRead, null);
            }
        }

    public class AsynchNetworkServer
    {

        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();
                ClientHandler handler =new ClientHandler(socketForClient);
                handler.StartRead();
            }
        }
    }








33.8.TcpListener
33.8.1.Listening for sockets
33.8.2.TcpListener Sample
33.8.3.Create a Socket server from TcpListener
33.8.4.Use NetworkStream to write to a client
33.8.5.Use TcpListener to create a Tcp server
33.8.6.Create BinaryWriter and BinaryReader from TcpListener
33.8.7.Time Server
33.8.8.Asynch Network Server