如何将 TCPListener 设置为始终侦听以及何时新连接丢弃当前 [英] How to set TCPListener to always listen and when new connection discard current

查看:41
本文介绍了如何将 TCPListener 设置为始终侦听以及何时新连接丢弃当前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想承认我不是 C# 中的最强者,我通过查看几个教程开发了这个程序,如果您能在答案中详细说明,我将不胜感激.
我希望我的 TCP 服务器始终侦听传入连接,并且当新的 TCP 客户端连接时,我希望它丢弃旧连接并使用新连接.

I want to admit I'm not the strongest in c# and I have developed this program by looking at several tutorials, I would appreciate a lot if you can be detailed in your answer.
I would like my TCP Server to always listening for incoming connections and when a new TCP Client connects, I want it to discard the old connection and use the new one.

我试图实现这个答案;https://stackoverflow.com/a/19387431/3540143
但我的问题是,当我模拟 TCP 客户端时,但不知何故上面的答案只会收到一条消息(我当前的代码接收所有发送的消息),我也尝试转换数据,所以我收到了与下面的代码相同,但没有任何成功.
此外,我认为上面的代码只是接受新客户端,而不会丢弃以前连接的客户端.

I have tried to implement this answer; https://stackoverflow.com/a/19387431/3540143
but my issue is the fact that when I'm simulating a TCP client, but somehow the answer above will only receive one message (my current code receive all messages sent), also I've tried to convert the data over so I receive it in same way as the code below but without any success.
Also the code above I believe is just accepting new clients, without discarding the previous connected clients.

我当前的代码可以处理连接并在断开连接后搜索新连接,我想这样做,所以我一直在寻找新连接,如果新客户端想要连接,我将丢弃当前让新通过

My current code, which can handle a connection and search for new connection once a disconnection have been made, I want to make it so I'm always looking for new connection and if a new client want to connect I'm discarding the current to let the new through

public class TCPListener
{
    public static void Listener()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on carPort.
            Int32 port = 5002;

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(IPAddress.Any, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                // Get a stream object for reading
                NetworkStream 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.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);
                }
                // Shutdown and end connection
                Console.WriteLine("Client close");
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            Console.WriteLine("Stop listening for new clients.");
            server.Stop();
        }

    }
}

如果有人需要我的问题的解决方案,那么这就是我应用 Cecilio Pardo 建议时代码的样子,效果非常好!

If anyone needs the solution for my issue then this is how the code looks like when I applied what Cecilio Pardo suggested, which works really great!

public class TCPListener
{
    Form form = new Form();
    public static void Listener()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on carPort.
            Int32 port = 5002;

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(IPAddress.Any, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                data = null;
                bool dataAvailable = false;
                // Get a stream object for reading
                NetworkStream stream = client.GetStream();

                int i;
                while (true)
                {
                    if (!dataAvailable)
                    {
                        dataAvailable = stream.DataAvailable;
                        //Console.WriteLine("Data Available: "+dataAvailable);
                        if (server.Pending())
                        {
                            Console.WriteLine("found new client");
                            break;
                        }
                    }

                    if (dataAvailable)
                    {
                        // Loop to receive all the data sent by the client.
                        i = stream.Read(bytes, 0, bytes.Length);
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                        Console.WriteLine("Received: {0}", data);
                        dataAvailable = false;
                    }

                    if (server.Pending())
                    {
                        Console.WriteLine("found new client");
                        break;
                    }
                }

                Console.WriteLine("Client close");
                // Shutdown and end connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            Console.WriteLine("Stop listening for new clients.");
            server.Stop();
        }

    }
}

推荐答案

当您处于内部 while 循环中时,您无法检查新连接.所以你必须在循环中添加这样的东西:

While you are in your inner while loop, you can't check for new connections. So you would have to add something like this inside the loop:

if ( server.Pending() ) break;

一旦另一个连接正在等待,这将退出您的循环.

That will exit your loop as soon as another connection is waiting.

另一个问题是 stream.Read 会阻塞直到一些数据可用,因此如果活动连接空闲,则不会处理新连接.所以你必须改变它,除非有一些数据,否则不要调用 Read,使用 stream.DataAvailable

Another problem is that stream.Read will block until some data is available, so new connections will not get handled if the active one is idle. So you have to change it, and not call Read unless there is some data, using stream.DataAvailable

这篇关于如何将 TCPListener 设置为始终侦听以及何时新连接丢弃当前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆