Exemplo n.º 1
0
        public void Start(IPEndPoint ip, int maxConnections, PBEEncryption encryption = null, bool dualMode = false)
        {
            if (IsRunning)
            {
                throw new InvalidOperationException("Server is already running.");
            }
            if (ip == null)
            {
                throw new ArgumentNullException(nameof(ip));
            }
            if (maxConnections <= 0)
            {
                throw new ArgumentException($"\"{nameof(maxConnections)}\" must be greater than 0.");
            }

            _listener = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            if (ip.AddressFamily == AddressFamily.InterNetworkV6)
            {
                _listener.DualMode = dualMode;
            }
            _listener.Bind(ip);
            _encryption = encryption;

            try
            {
                _maxConnections = maxConnections;
                _listener.Listen(maxConnections);
                _listener.BeginAccept(OnClientConnected, null);
            }
            catch (Exception ex)
            {
                NotifyError(ex);
                Stop();
            }
        }
Exemplo n.º 2
0
        public bool Connect(IPEndPoint ip, int millisecondsTimeout, PBEEncryption encryption = null)
        {
            if (ip == null)
            {
                throw new ArgumentNullException(nameof(ip));
            }
            if (millisecondsTimeout < -1)
            {
                throw new ArgumentException($"\"{nameof(millisecondsTimeout)}\" is invalid.");
            }

            Disconnect(true);
            _socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                if (_socket.BeginConnect(ip, null, null).AsyncWaitHandle.WaitOne(millisecondsTimeout))
                {
                    IsConnected = true;
                    RemoteIP    = ip;
                    _encryption = encryption;
                    BeginReceive();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                NotifyError(ex);
            }
            Disconnect(false);
            return(false);
        }
Exemplo n.º 3
0
 public void Disconnect(bool notify)
 {
     if (IsConnected)
     {
         IsConnected = false;
         RemoteIP    = null;
         _encryption = null;
         try
         {
             _socket.Shutdown(SocketShutdown.Both);
         }
         catch (Exception ex)
         {
             NotifyError(ex);
         }
         _socket.Dispose();
         _socket = null;
         if (notify)
         {
             Disconnected?.Invoke(this, EventArgs.Empty);
         }
     }
 }
Exemplo n.º 4
0
 internal PBEServerClient(Socket socket, PBEEncryption encryption)
 {
     Socket      = socket;
     IP          = (IPEndPoint)socket.RemoteEndPoint;
     _encryption = encryption;
 }