插座没有正确关闭

时间:2017-05-09 19:06:43

标签: c# .net sockets tcpclient

使用提供的代码here

在120秒内连续运行时,我的机器上出现SocketException

失败

Only one usage of each socket address (protocol/network address/port) is normally permitted 127.0.0.1:24125

at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)

at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)

  • Windows 10 x64
  • socket.Close();之后添加socket.Receive(receiveBuffer);不会做任何事情。也许很明显,因为Dispose()无论如何都应该自动调用Close()
  • 如果移植到F#,行为没有区别。所以它与.NET库的使用方式有关,而不是任何特定于语言的语言(再次,如果这很明显,那就很抱歉)。
  • 如果从Windows命令提示符或调试器运行输出.exe,也会出现同样的情况。
  • 在代码中放置socket后,等待超过120秒会重置套接字,并且可以再次使用它而不会出错。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace tcpTestCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string response = "Hello";
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

            if (ipAddress != null)
            {
                IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, 24125);
                byte[] receiveBuffer = new byte[100];

                try
                {
                    using (TcpClient client = new TcpClient(serverEndPoint))
                    {
                        using (Socket socket = client.Client)
                        {
                            socket.Connect(serverEndPoint);

                            byte[] data = Encoding.ASCII.GetBytes(response);

                            socket.Send(data, data.Length, SocketFlags.None);

                            socket.Receive(receiveBuffer);

                            Console.WriteLine(Encoding.ASCII.GetString(receiveBuffer));
                        }
                    }
                }
                catch (SocketException socketException)
                {
                    Console.WriteLine("Socket Exception : ", socketException.Message);
                    throw;
                }

                Console.ReadLine();
            }
        }
    }
}

0 个答案:

没有答案