Create server with TcpListener - CSharp Network

CSharp examples for Network:TCP

Description

Create server with TcpListener

Demo Code

using System;//from   w  w  w  . j  a v  a  2  s. c o m
using System.IO;
using System.Net;
using System.Threading;
using System.Net.Sockets;
class MainClass
{
    private static bool terminate;
    public static bool Terminate { get { return terminate; } }
    private static int ClientNumber = 0;
    private static TcpListener listener;
    public static void Main()
    {
        using (FileStream fs = new FileStream("test.bin", FileMode.Create))
        {
            fs.SetLength(100000);
        }
        try
        {
            listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8000);
            Console.WriteLine("Starting TcpListener...");
            terminate = false;
            listener.Start();
            listener.BeginAcceptTcpClient(ConnectionHandler, null);
            Console.WriteLine("Server awaiting connections. Press Enter to stop server.");
            Console.ReadLine();
        }
        finally
        {
            Console.WriteLine("Server stopping...");
            terminate = true;
            if (listener != null) listener.Stop();
        }
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Server stopped. Press Enter");
        Console.ReadLine();
    }
    private static void ConnectionHandler(IAsyncResult result)
    {
        TcpClient client = null;
        try
        {
            client = listener.EndAcceptTcpClient(result);
        }
        catch (ObjectDisposedException)
        {
            return;
        }
        Console.WriteLine("Dispatcher: New connection accepted.");
        listener.BeginAcceptTcpClient(ConnectionHandler, null);
        if (client != null)
        {
            Interlocked.Increment(ref ClientNumber);
            string clientName = "Client " + ClientNumber.ToString();
            Console.WriteLine("Dispatcher: Creating client handler ({0}).", clientName);
            new ClientHandler(client, clientName);
        }
    }
}
public class ClientHandler
{
    private TcpClient client;
    private string ID;
    private int bufferSize = 2048;
    private byte[] buffer;
    private FileStream fileStream;
    private bool stopDataTransfer;
    internal ClientHandler(TcpClient client, string ID)
    {
        this.buffer = new byte[bufferSize];
        this.client = client;
        this.ID = ID;
        Thread thread = new Thread(ProcessConnection);
        thread.IsBackground = true;
        thread.Start();
    }
    private void ProcessConnection()
    {
        using (client)
        {
            using (BinaryReader reader = new BinaryReader(client.GetStream()))
            {
                if (reader.ReadString() == "RequestConnect")
                {
                    using (BinaryWriter writer = new BinaryWriter(client.GetStream()))
                    {
                        writer.Write("OK");
                        Console.WriteLine(ID + ": Connection established.");
                        string message = "";
                        while (message != "Disconnect")
                        {
                            try
                            {
                                message = reader.ReadString();
                            }
                            catch
                            {
                                message = "Disconnect";
                            }
                            if (message == "RequestData")
                            {
                                Console.WriteLine(ID + ": Requested data. ", "Sending...");
                                fileStream = new FileStream("test.bin", FileMode.Open, FileAccess.Read);
                                writer.Write(fileStream.Length.ToString());
                                stopDataTransfer = false;
                                StreamData(null);
                            }
                            else if (message == "Disconnect")
                            {
                                Console.WriteLine(ID + ": Client disconnecting...");
                                stopDataTransfer = true;
                            }
                            else
                            {
                                Console.WriteLine(ID + ": Unknown command.");
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine(ID + ": Could not establish connection.");
                }
            }
        }
        Console.WriteLine(ID + ": Client connection closed.");
    }
    private void StreamData(IAsyncResult asyncResult)
    {
        if (asyncResult != null)
        {
            try
            {
                client.GetStream().EndWrite(asyncResult);
            }
            catch
            {
                fileStream.Close();
                return;
            }
        }
        if (!stopDataTransfer && !MainClass.Terminate)
        {
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            if (bytesRead > 0)
            {
                Console.WriteLine(ID + ": Streaming next block.");
                client.GetStream().BeginWrite(buffer, 0, buffer.Length, StreamData, null);
            }
            else
            {
                Console.WriteLine(ID + ": File streaming complete.");
                fileStream.Close();
            }
        }
        else
        {
            Console.WriteLine(ID + ": Client disconnected.");
            fileStream.Close();
        }
    }
}

Result


Related Tutorials