简体   繁体   中英

Send message to active tcp client from different function in c#

i want to send message to all connected connection, the code is:

using 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");
    }
}

Thanks:)

Assuming there is some mechanism somewhere that prevents the app from exiting as soon as MulticastText is over and done, you just need to lift your server to a scope where both methods can access it:

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

You also said in comments:

trying to define server to block level scope like: static ChatServer server; got this message: Object reference not set to an instance of an object.

Note that just because you make a variable declaration at class level/just because it's static doesn't mean it automatically becomes filled with an instance of an object so you probably lifted the declaration but then didn't anywhere have a server = new ChatServer(...) line to actually fill it with an instance of anything

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM