如何在tcplistener.accepttcpclient上引发事件

本文关键字:事件 accepttcpclient tcplistener | 更新日期: 2023-09-27 18:29:23

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

如何在tcplistener.accepttcpclient上引发事件

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