如何设置TCPListener始终监听,并在新连接时丢弃当前连接。

3

我想承认我在C#方面并不是最强的,我通过查看几个教程来开发这个程序,如果您能详细回答我的问题,我将不胜感激。
我希望我的TCP服务器始终监听传入的连接,当一个新的TCP客户端连接时,我希望它放弃旧连接并使用新连接。

我尝试实现这个答案:https://dev59.com/sWIk5IYBdhLWcg3wUsrv#19387431
但我的问题是,当我模拟TCP客户端时,上面的答案只会接收一条消息(而我的当前代码会接收所有发送的消息),我也尝试转换数据,以便以与下面的代码相同的方式接收它,但没有成功。
此外,我认为上面的代码仅接受新客户端,而不会丢弃先前连接的客户端。

我的当前代码可以处理连接,并在断开连接后搜索新连接,我希望始终寻找新连接,如果新客户端要连接,则放弃当前连接,让新客户端通过

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建议的代码,非常有效!

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

    }
}
2个回答

1

当你处于内部的 while 循环中时,无法检查新连接。因此,你需要在循环内添加类似以下内容的代码:

if ( server.Pending() ) break;

那将在等待另一个连接时退出循环。
另一个问题是,stream.Read会阻塞直到有数据可用,因此如果活动连接处于空闲状态,则不会处理新连接。因此,您需要进行更改,并且仅在有数据时调用Read,使用stream.DataAvailable。

经过一番努力,我终于通过你的解决方案使所有东西都能正常工作了!非常感谢你! - MikeyR

1

这是我正在使用的代码,目前效果还不错,我刚开始开发这种类型的应用程序。如果我对这段代码进行了重大更改或发现了错误,我会进行更新:

class ClientListener
{
    const int PORT_NO = 4500;
    const string SERVER_IP = "127.0.0.1";
    private TcpListener listener;

    public async Task Listen()
    {
        IPAddress localAddress = IPAddress.Parse(SERVER_IP);
        listener = new TcpListener(localAddress, PORT_NO);
        Console.WriteLine("Listening on: " + SERVER_IP + ":" + PORT_NO);
        listener.Start();

        while (true)
        {
            // Accept incoming connection that matches IP / Port number
            // We need some form of security here later
            TcpClient client = await listener.AcceptTcpClientAsync();

            if (client.Connected)
            {
                // Get the stream of data send by the server and create a buffer of data we can read
                NetworkStream stream = client.GetStream();
                byte[] buffer = new byte[client.ReceiveBufferSize];

                int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);

                // Convert the data recieved into a string
                string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Recieved Data: " + data);
            }
        }
    }

    public void StopListening()
    {
        listener.Stop();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接