C# 侦听和接受连接的简单 Telnet 控制台

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19169893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:18:52  来源:igfitidea点击:

Simple Telnet console that listens and accepts connections

c#console-applicationtelnettcplistener

提问by John Smith

I am new to Telnet and C# and I am trying to create a simple console program. I need a TCP listener that starts up, listens for incoming networking connections and sends a response back. I don't really care for the incoming message but I need to accept it so the client thinks that the connection was successful. This TCP listener will respond with “Hello”. I just need to make sure that it starts up cleanly and close the TCP listener gracefully without throwing any exceptions. I need to use “Telnet localhost 9090” to connect to the TCP listener on your laptop on port 9090.

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

Can you help?

你能帮我吗?

采纳答案by Jaycee

Use the TCPListenerclass. The example echoes the string sent to it from the client provided in the second set of code so it sends the response Howdy. You can test this when you run the client code below, which calls Socket.Receiveto get the string back from the server:

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

回答by ShadowHunter

You can use this Simple Telnet Server I found on Internet: https://gist.github.com/UngarMax/6394321573dc0791dff9/

您可以使用我在 Internet 上找到的这个简单的 Telnet 服务器:https: //gist.github.com/UngarMax/6394321573dc0791dff9/

You can have this code as a base for the program you're planning to build.

您可以将此代码作为您计划构建的程序的基础。