简体   繁体   English

C#-C:停止阻止子线程上的侦听套接字

[英]C# - C:stop blocking listen socket on a child thread

My program: 我的程序:
I create 2 threads:Thread 1 with a listen socket,and thread 2 do somethings. 我创建了2个线程:带有侦听套接字的线程1,以及线程2做某事。
But thread 1 blocks program and i can not start thread 2 until listen socket on thread 1 receives data. 但是线程1阻止了程序,并且直到线程1上的侦听套接字接收到数据后,我才能启动线程2。 But i need 2 threads run at the same time,and don`t need to keep in sync between 2 threads.(but still in same program). 但是我需要同时运行2个线程,并且不需要在2个线程之间保持同步。(但仍在同一程序中)。
How to do it??? 怎么做??? My code like this: 我的代码是这样的:

 Thread thread1 = new Thread(new ThreadStart(a.thread1)); Thread thread2 = new Thread(new ThreadStart(b.thread2)); try { thread1.Start(); thread2.Start(); thread1.Join(); // Join both threads with no timeout // Run both until done. thread2.Join(); } 

Program stop at thread 1(listen socket). 程序在线程1(侦听套接字)处停止。
And i don't want to use non-blocking socket(I am using blocking socket). 而且我不想使用非阻塞套接字(我正在使用阻塞套接字)。
Listen socket should block child thread,but should not block my program. 侦听套接字应阻止子线程,但不应阻止我的程序。

I have just recently had this self same issue and resolved it like this: 我最近遇到了这个相同的问题,并按以下方式解决了它:

    private static void StartServers()
{
    for (int i = Convert.ToInt32(ConfigurationManager.AppSettings.Get("PortStart"));
                    i <= Convert.ToInt32(ConfigurationManager.AppSettings.Get("PortEnd"));
                    i++)
                {
                    var localAddr = IPAddress.Parse(ConfigurationManager.AppSettings.Get("IpAddress"));
                    var server = new TcpListener(localAddr, i);
                    Servers.Add(server);
                    server.Start();
                    StartAccept(server);
                }
}
private static void StartAccept(TcpListener server)
    {
        server.BeginAcceptTcpClient(OnAccept, server);
    }
private static void OnAccept(IAsyncResult res)
    {
        var client = new TcpClient();
        try
        {
            Console.ForegroundColor = Console.ForegroundColor == ConsoleColor.Red
                ? ConsoleColor.Green
                : ConsoleColor.White;
            var server = (TcpListener) res.AsyncState;
            StartAccept(server);
            client = server.EndAcceptTcpClient(res);
            Console.WriteLine("Connected!\n");
            var bytes = new byte[512];
            // Get a stream object for reading and writing
            var stream = client.GetStream();


            int i;

            // Loop to receive all the data sent by the client.
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                // Translate data bytes to a ASCII string.
                var data = Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine("Received: {0} \n", data);

                // Process the data sent by the client.
                data = InterpretMessage(data);
                var msg = Encoding.ASCII.GetBytes(data);

                // Send back a response.
                stream.Write(msg, 0, msg.Length);
                Console.WriteLine("Sent: {0} \n", data);
            }
        }
        catch (Exception exception)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            client.Close();
            Console.WriteLine(exception.Message);
        }
    }

Basically what this does is creates an asynchronous receiving system in which you can have multiple servers listening to multiple ports simultaneously. 基本上,这是创建一个异步接收系统,在该系统中,您可以让多个服务器同时侦听多个端口。 Bearing in mind that you can only ever have one listener per port. 请记住,每个端口只能有一个侦听器。

In your example, you can simply call the StartServers method and then directly afterwards, continue with whatever your application is doing. 在您的示例中,您可以简单地调用StartServers方法,然后直接调用之后,继续执行应用程序正在执行的任何操作。

In order for this to work for a single server on a single port, merely remove the looping in StartServers and configure 1 TcpListener and start it up. 为了使它在单个端口上的单个服务器上工作,只需删除StartServers中的循环并配置1 TcpListener并启动它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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