SocketException - 无法使用Shutdown或Close

时间:2018-02-15 10:59:31

标签: c# sockets

我试图通过套接字以5秒的间隔发送消息。

为了测试它,我有基本的服务器套接字(它会监听来电)实现:

    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.  
        // Dns.GetHostName returns the name of the   
        // host running the application.  
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.  
        Socket listener = new Socket(ipAddress.AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and   
        // listen for incoming connections.  
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.  
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.  
                Socket handler = listener.Accept();
                data = null;

                // An incoming connection needs to be processed.  
                while (true)
                {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    //if (data.IndexOf("<EOF>") > -1)
                    //{
                        break;
                    //}
                }

                // Show the data on the console.  
                Console.WriteLine("Text received : {0}", data);

                // Echo the data back to the client.  
                //byte[] msg = Encoding.ASCII.GetBytes(data);

                // handler.Send(msg);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }

套接字,它发送我以多种方式实现的消息,它们都没有工作,我终于被建议每次使用它时连接和关闭套接字(不是每5秒就会使用它 - 有些条件需要是满意,以建立联系)。无论如何,我最终得到这样的东西:

    private static void CheckDbAndSendMessage()
    {
        var entities = // custom ORM read from DB ;

        // no new records
        if (entities.Count == 0)
            return;

        HashSet<string> messages = new HashSet<string>();
        foreach (var entity in entities)
        {
            messages.Add(entity.Description + " --- " + entity.Operator);
            entity.Status = 10;
        }

        try
        {
            SendMessage(messages);
        }
        catch(Exception ex)
        {
            //implemented error handling
        }
    }

    /// <summary>
    /// Sends messages over specified channel.
    /// </summary>
    /// <param name="messages"></param>
    /// <exception cref="Exception">Thrown when socket connections fails.</exception>
    private static void SendMessage(HashSet<string> messages)
    {
        _sender.Connect(_remoteEP);
        foreach (var message in messages)
        {
            _sender.Send(System.Text.Encoding.ASCII.GetBytes(message));
        }

        // When app stops, it will be released.
        _sender.Shutdown(SocketShutdown.Both);
        _sender.Close();

    }

当我像这样运行时,_sender.Close()会破坏套接字,如here所述。因此,将首先建立连接,但之后我将在另一个呼叫中获得ObjectDisposedexception。好的,所以我删除了那一行,只使用_sender.Shutdown(SocketShutdown.Both)并在第二个连接上得到例外:

  

断开套接字后,您只能从另一个EndPoint异步重新连接。

那么,解决它的正确方法是什么?我花了几个小时无处可去......

0 个答案:

没有答案