'programming/C#'에 해당되는 글 8건

  1. 2011.04.20 Thread TCP Server

Thread TCP Server

programming/C# 2011. 4. 20. 01:03
반응형
http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server


using
System;
using System.Net;
using System.Net.Sockets;

/// <summary>
/// Multithreaded  routine to handle concurrent Tcp connections on a single endpoint
/// </summary>
public class TcpHandler
{
    public bool listening;
    public TcpListener listener;
   
    public void Main()
        {
                Byte[] ip = {127, 0, 0, 1};
        IPEndPoint endPt = new IPEndPoint(new IPAddress(ip), 3000);

        this.listener = new TcpListener(endPt);
        this.listener.Start();

        Console.WriteLine("Listening");

        this.listening = true;
        listener.BeginAcceptTcpClient(HandleRequestAsync, null);

        Console.WriteLine("Press 'Enter' to exit...");
        Console.Read();
        listening = false;

        listener.Stop();
        }

    public void HandleRequestAsync(IAsyncResult ar)
    {
        TcpClient client;

        client = listener.EndAcceptTcpClient(ar);
        if (listening)
        {
            listener.BeginAcceptTcpClient(HandleRequestAsync, null);

        }

        // Handle the client connection here
    }
}
반응형
Posted by 공간사랑
,