如何在tcplistener.accepttcpclient上引发事件

时间:2016-01-07 07:49:37

标签: c# events tcplistener

我现在正在设计一个Tcp服务器。我希望在客户端连接到我的服务器时触发事件。怎么办?

1 个答案:

答案 0 :(得分:3)

public class Server
{
    private TcpListener _server;
    private bool _isServerWorking = false;
    private TcpClient _client;

    public Server(string host, int port)
    {
        var ipAddress = IPAddress.Parse(host);
        _server = new TcpListener(ipAddress, port);
    }

    public async Task StartAsync()
    {
        _server.Start();
        _isServerWorking = true;
        while(_isServerWorking)
        {
            _client = await _server.AcceptTcpClientAsync();
            ServerConnectedEventArgs args = new ServerConnectedEventArgs(_client);
            OnServerConnected(args);
            ThreadPool.QueueUserWorkItem(ConnectClientsThredProc, _client);
        }
    }

    public void Stop()
    {
        _isServerWorking = false;
        _server.Stop();
    }


    private static void ConnectClientsThredProc(object obj)
    {
        var client = (TcpClient)obj;
    }



    public event ServerConnectedEventHandler ServerConnectedEvent;
    private void OnServerConnected(ServerConnectedEventArgs e)
    {
        ServerConnectedEvent(this, e);
    }

}

最后,我找到了解决方案。收到客户端连接后,我将举起活动。这是事件数据和事件委托。

public class ServerConnectedEventArgs: EventArgs
{
    public TcpClient Client { set; get; }
    public ServerConnectedEventArgs(TcpClient client)
    {
        Client = client;
    }
}

public delegate void ServerConnectedEventHandler(object sender, ServerConnectedEventArgs e);