处理服务器关闭

时间:2016-12-29 04:45:43

标签: c# sockets

我对C#中的套接字很新,我正在尝试处理关闭客户端的服务器,我希望客户端能够连续连接,所以当他们无法连接时,他们会继续尝试,当服务器关闭时,我希望他们在服务器恢复时立即尝试重新连接。

Program.cs [客户]

using System;

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

    namespace Sythic
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.Title = "Sythic Client";
                Console.WriteLine();

                ConnectionManager cm = new ConnectionManager();
                cm.Connect();

                Console.ReadKey(true);
            }
        }
    }

ConnectionManager.cs [客户端]

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

namespace Sythic
{
    class ConnectionManager
    {
        private Socket _socket;
        private Thread _thread;
        private System.Timers.Timer _timer;
        private bool _needsReconnecting;

        public ConnectionManager()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
        }

        public void Connect()
        {
            Console.WriteLine("Attempting to connect...");
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3459);

            try
            {
                _socket.Connect(ipep);

                _timer = new System.Timers.Timer();
                _timer.Elapsed += new ElapsedEventHandler(OnTick);
                _timer.Interval = 1000;
                _timer.Enabled = true;

                _thread = new Thread(ReceivedData);
                _thread.Start();
            }
            catch (SocketException)
            {
                Console.WriteLine("Failed to connect to server, retrying...");
                Connect();
            }
        }

        private void OnTick(object source, ElapsedEventArgs e)
        {
            if (!_socket.Connected && _needsReconnecting)
            {
                Console.WriteLine("The client is disconnect, we should start trying to re-connect now..");
                Connect();
                _needsReconnecting = false;
            }
        }

        private void ReceivedData()
        {
            byte[] buffer;
            int readBytes;

            while (true)
            {
                if (!_socket.Connected)
                {
                    return;
                }

                try
                {
                    buffer = new byte[_socket.SendBufferSize];
                    readBytes = _socket.Receive(buffer);

                    if (readBytes > 0)
                    {
                        Console.WriteLine("Received something...");
                    }
                }
                catch (SocketException)
                {
                    ServerClosed();
                }
            }
        }

        private void ServerClosed()
        {
            Console.WriteLine("Oh no, the server closed.. :/");
            // not sure what to do here, need to research how to disconnect, or does it disconnect automatically because no server? hmm...
            _needsReconnecting = true;
        }
    }
}

那么问题是什么? 这一行:

_socket.Connect(ipep);
Connect()方法中的

类型' System.InvalidOperationException'的例外情况发生在System.dll中但未在用户代码中处理

附加信息:一旦套接字断开连接,您只能异步重新连接,并且只能重新连接到另一个EndPoint。必须在不会退出的线程上调用BeginConnect,直到操作完成。

0 个答案:

没有答案