我无法连接以测试使用TcpListener

时间:2015-11-21 02:31:46

标签: c# .net sockets tcplistener

免责声明:这是我第一次涉足任何直接与tcp / socket相关的东西。我已阅读 - the - - following - - resources - 我正在努力想出一个非常简单的测试应用程序。

我正在尝试开发一个使用TcpListener对象运行的本地服务器。我可以很好地实例化它并运行netstat以查看处于LISTENING状态的端口。但是,我无法telnet或创建测试客户端来手动连接。 Telnet简单地说它无法打开连接。尝试测试客户端应用程序会抛出异常

  

System.dll

中发生了'System.Net.Sockets.SocketException'类型的未处理异常      

附加信息:通常只允许使用每个套接字地址(协议/网络地址/端口)

this SO问题中,提问者最终通过故障NIC解决了问题。我怎么能找到它?

这让我感到困惑。我如何测试或连接到服务器?这是我的代码。

对于服务器:

using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace TcpConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var localPort = ConfigurationManager.AppSettings["localPort"];
            var portNumber = int.Parse(localPort);

            var maxConnections = ConfigurationManager.AppSettings["maxConnections"];
            var maxConnectionsNumber = int.Parse(maxConnections);

            Console.WriteLine("Preparing to start server on port {0}", portNumber);
            Console.WriteLine("Max connections: {0}", maxConnectionsNumber);

            var ipHostInfo = Dns.GetHostEntry("localhost");
            var ipAddress = ipHostInfo.AddressList[0];
            var localEndPoint = new IPEndPoint(ipAddress, portNumber);

            Console.WriteLine("Starting server with local IP {0}", ipAddress);

            var listener = new TcpListener(localEndPoint);
            listener.Start(maxConnectionsNumber);

            Console.WriteLine();
            Console.WriteLine("Server started...");
            Console.WriteLine();

            while (true)
            {
                var socket = listener.AcceptSocket();
                Task.Factory.StartNew(() =>
                {
                    ProcessSocket(socket);
                });
            }
        }

        private static async void ProcessSocket(Socket socket)
        {
            try
            {
                using (var stream = new NetworkStream(socket))
                using (var reader = new StreamReader(stream))
                using (var writer = new StreamWriter(stream))
                {
                    writer.AutoFlush = true;

                    var received = await reader.ReadToEndAsync();

                    Console.WriteLine("Received: " + received);
                }

                socket.Close();
                socket.Dispose();
            }
            catch (Exception exception)
            {
                Console.WriteLine("There was an error processing a message.");
                Console.WriteLine(exception);
            }
        }
    }
}

看到上面的代码正在运行:

TcpConsole running and getting to "Server started..." Seeing the connection in the LISTENING state with netstat

对于测试应用程序:

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

namespace TcpConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var ipHostInfo = Dns.GetHostEntry("localhost");
            var ipAddress = ipHostInfo.AddressList[0];
            var remoteEndPoint = new IPEndPoint(ipAddress, 3245);

            var client = new TcpClient(remoteEndPoint);

            using (var stream = client.GetStream())
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream))
            {
                writer.AutoFlush = true;

                string input;

                while((input = Console.ReadLine()) != "exit")
                {
                    writer.WriteLine(input);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

TCP / IP连接具有本地IP地址和端口,以及远程IP地址和端口。

通常,端口号一次只能分配给一个套接字。该错误消息表明尝试将多个套接字与相同的端口号关联。

可以在客户端代码中找到原因:

var client = new TcpClient(remoteEndPoint);

TcpClient构造函数的此重载接受指定本地端点的IPEndPoint。也就是说,当构造TcpClient时,它将被绑定到remoteEndPoint指定的端口号,该端口号失败,因为该端口号已被服务器应用程序使用。

要解决此问题,请使用无参数TcpClient构造函数,然后将remoteEndPoint传递给Connect调用:

var client = new TcpClient();

client.Connect(remoteEndPoint);