首页 > 解决方案 > 从 C# 中的不同函数向活动 tcp 客户端发送消息

问题描述

我想向所有连接的连接发送消息,代码是:

使用 NetCoreServer

class Program
{
    static void Main(string[] args)
    {
        var server = new ChatServer(context, IPAddress.Any, Port);
        server.Start();
        server.MulticastText("Send text to client");
    }

    public static void TimedBroadcast(object source, ElapsedEventArgs e)
    {
        // i want to send broadcast message to connected client within this function to Main() function
        server.MulticastText("Send broadcast status to client with cron task");
    }
}

谢谢 :)

标签: c#

解决方案


假设某处有某种机制阻止应用程序在 MulticastText 结束并完成后立即退出,您只需将您提升server到两种方法都可以访问它的范围:

class Program
{
    private static ChatServer _server = new ChatServer(context, IPAddress.Any, Port); //not sure where context, and Port come from

    static void Main(string[] args)
    {
        _server.Start();
        _server.MulticastText("Send text to client");
    }

    static void TimedBroadcast(object source, ElapsedEventArgs e)
    {
        // i want to send broadcast message to connected client within this function to Main() function
        _server.MulticastText("Send broadcast status to client with cron task");
    }
}

你还在评论中说:

尝试将服务器定义为块级范围,例如:静态 ChatServer 服务器;收到此消息:对象引用未设置为对象的实例。

请注意,仅仅因为您在类级别进行了变量声明/仅仅因为它是静态的并不意味着它会自动填充对象的实例,因此您可能解除了声明,但没有任何地方可以server = new ChatServer(...)实际填充它任何事物的实例


推荐阅读