简单的Telnet控制台,可监听并接受连接。

9
我刚接触Telnet和C#,尝试创建一个简单的控制台程序。我需要一个TCP监听器,可以启动并监听传入的网络连接,并发送响应。我不关心传入的消息,但需要接受它,以便客户端认为连接成功。这个TCP监听器将会回复“Hello”。
我只需要确保它可以干净地启动并优雅地关闭TCP监听器而不抛出任何异常。我需要使用“Telnet localhost 9090”来连接到您笔记本电脑上的TCP监听器端口9090上。

你能分享一下你尝试过的内容吗? - StormeHawke
我使用了MSDN的TCPListener类示例页面上找到的示例代码。它与Jaycee提供的答案相同。但是,我不知道@Jaycee第二组代码是用来做什么的。 - John Smith
@RuvimSkochko 我稍微修改了MSDN的示例,以便在正确的端口上进行侦听并发送响应。第二个完整的控制台应用程序示例是一个客户端,可以单独运行,作为服务器快速测试的一部分。 - Jaycee
@Jaycee 好的,我现在明白你做了什么。我在 MSDN 网站上读到他们的示例代码中,停止方法不会关闭任何已接受的连接。我如何“优雅地”关闭已接受的连接(用缺乏更好措辞的话来说)? - John Smith
@RuvimSkochko 这只是确保对已接受的任何客户端都调用 client.Close(); 的情况。不确定您正在做什么,但如果您只调用 Stop,则并不意味着您当前打开的任何连接都将关闭。您可能需要实现一些整理工作-保留您创建的 TcpClient 列表,并在 finally 部分中运行列表,对每个客户端调用 Close-然后调用 Stop。这样可以在出现异常时整理事物。服务器如何管理客户端连接是应用程序特定的。 - Jaycee
2个回答

22

使用TCPListener类。该示例会回显从第二组代码中提供的客户端发送给它的字符串,因此它会发送响应“Howdy”。您可以通过运行下面的客户端代码来测试此功能,该代码调用Socket.Receive从服务器获取字符串:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace tcplistener
{
    class Program
    {
        static void Main(string[] args)
        {
             TcpListener server = null;
        try
        {
            Int32 port = 9090;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            server = new TcpListener(localAddr, 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. 
                // You could also user server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Hello!");

                data = null;

                // Get a stream object for reading and writing
                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);

                    // Process the data sent by the client.
                    data = data.ToUpper();

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);
                    Console.WriteLine("Sent: {0}", data);
                }

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


        Console.WriteLine("\nHit enter to continue...");
        Console.Read();

        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace tcpconnect
{
    class Program
    {
        static void Main(string[] args)
        {
            Connect1("127.0.0.1", 9090);

            Console.Read();
        }

        // Synchronous connect using IPAddress to resolve the  
        // host name. 
        public static void Connect1(string host, int port)
        {
            IPAddress[] IPs = Dns.GetHostAddresses(host);

            Socket s = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);

            Console.WriteLine("Establishing Connection to {0}",
                host);
            s.Connect(IPs[0], port);

            byte[] howdyBytes = Encoding.ASCII.GetBytes("Howdy");
            s.Send(howdyBytes);
            byte[] buffer = new byte[50];
            s.Receive(buffer);
            Console.Write(Encoding.ASCII.GetString(buffer));
            Console.WriteLine("Connection established");
        }
    }
}

我想在.NET Core中尝试您的示例,但是似乎他们没有实现server.AcceptSocket()或 server.AcceptTcpClient(); 我该如何解决这些调用? - Håkon Seljåsen
2
.NET Core的源代码在GitHub上,我检查了TcpListener类,这两种方法都在那里:https://github.com/dotnet/corefx/blob/master/src/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs - Jaycee

6

我刚刚更新了链接,但你能否添加更多关于这个解决方案的上下文信息?目前它几乎只是一个链接式的答案。 - PeterJ

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