Exemple #1
0
        private void CreateSocket()
        {
            try
            {
                sock = _socketFactory.CreateSocket(endpoint.IpAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp, _enableDualMode);
            }
            catch (SocketCreateException ex)
            {
                if (_enableDualMode && endpoint.IpAddress.Equals(IpAddressInfo.IPv6Any) &&
                    (string.Equals(ex.ErrorCode, "AddressFamilyNotSupported", StringComparison.OrdinalIgnoreCase) ||
                     // mono on bsd is throwing this
                     string.Equals(ex.ErrorCode, "ProtocolNotSupported", StringComparison.OrdinalIgnoreCase)))
                {
                    endpoint        = new IpEndPointInfo(IpAddressInfo.Any, endpoint.Port);
                    _enableDualMode = false;
                    sock            = _socketFactory.CreateSocket(endpoint.IpAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp, _enableDualMode);
                }
                else
                {
                    throw;
                }
            }

            sock.Bind(endpoint);

            // This is the number TcpListener uses.
            sock.Listen(2147483647);

            sock.StartAccept(ProcessAccept, () => _closed);
            _closed = false;
        }
        public EndPointListener(
            IPAddress address,
            int port,
            bool secure,
            string certFolderPath,
            X509Certificate2 defaultCert
            )
        {
            if (secure)
            {
                _secure = secure;
                _cert   = getCertificate(port, certFolderPath, defaultCert);
                if (_cert == null)
                {
                    throw new ArgumentException("Server certificate not found.");
                }
            }

            _endpoint = new IPEndPoint(address, port);
            _socket   = SocketUtilsFactory.Utils.CreateSocket(address);
            _socket.Bind(_endpoint);
            _socket.Listen(500);
            var args = SocketUtilsFactory.Utils.CreateSocketAsyncEventArgs();

            args.UserToken  = this;
            args.Completed += onAccept;
            _socket.AcceptAsync(args);
            _prefixes     = new Dictionary <ListenerPrefix, HttpListener> ();
            _unregistered = new Dictionary <HttpConnection, HttpConnection> ();
        }
Exemple #3
0
        public IEnumerable <Task> StartServer()
        {
            var serverSocket = _socket
                               .Bind(_configuration["ip"], int.Parse(_configuration["port"]))
                               .Listen(32);

            while (true)
            {
                var acceptedConnection = serverSocket.Accept();
                yield return(Task.Run(() =>
                {
                    try
                    {
                        ProcessAcceptedConnection(acceptedConnection);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                        throw;
                    }
                    finally
                    {
                        acceptedConnection.Dispose();
                    }
                }));
            }
        }
Exemple #4
0
 void IListenable.Bind(int Port)
 {
     m_Socket.Bind(Port);
     m_Host.AcceptEvent += Accept;
     m_Enable            = true;
     ThreadPool.QueueUserWorkItem(Run, state: null);
 }
Exemple #5
0
        public void Launch()
        {
            m_Socket.Bind(Port: 0);
            m_Enable = true;

            _Procresser.Start();
        }
Exemple #6
0
        public string StartServer(int port)
        {
            IPAddress[] addresses      = null;
            string      serverHostName = "";
            IPHostEntry ipEntry;

            try
            {
                serverHostName = _dns.GetHostName();
                ipEntry        = _dns.GetHostByName(serverHostName);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            addresses = ipEntry.AddressList;
            if (addresses == null || addresses.Length < 1)
            {
                return("Couldnt get local address.");
            }

            _listener.Bind(new IPEndPoint(addresses[0], port));
            _listener.Listen(10);
            _listener.BeginAccept(new AsyncCallback(AcceptClient), _listener);

            return($"Listening On: {addresses[0]} : {port}");
        }
Exemple #7
0
 public void Bind(EndPoint endPoint)
 {
     if (active)
     {
         throw new InvalidOperationException("Peer is already active");
     }
     active = true;
     socket.Bind(endPoint);
 }
Exemple #8
0
        public async Task StartAsync(IPEndPoint endPoint)
        {
            _listener = _socketFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listener.Bind(endPoint);

            _cancellation = new CancellationTokenSource();

            await ListenAsync(_cancellation.Token);
        }
Exemple #9
0
        public async Task StartAsync(IPEndPoint endPoint)
        {
            _listener = _socketFactory(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            unchecked
            {
                _listener.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
            }
            _listener.Bind(endPoint);

            _cancellation = new CancellationTokenSource();

            await ListenAsync(PreparePacket, _cancellation.Token);
        }
Exemple #10
0
        public void Start(ISocket socket, UInt16 port)
        {
            Stop();

            System.Net.IPEndPoint ipEnd = new System.Net.IPEndPoint(System.Net.IPAddress.Any, port);

            _listeningSocket = socket;

            _listeningSocket.Bind(ipEnd);

            // Accept only one connection for now...
            _listeningSocket.Listen(1);

            _listeningSocket.BeginAccept(new AsyncCallback(ClientConnect), null);
        }
Exemple #11
0
        // Bind(u32 socket, buffer<nn::socket::sockaddr_in, 0x21, 0x10> addr) -> (i32 ret, u32 bsd_errno)
        public ResultCode Bind(ServiceCtx context)
        {
            int socketFd = context.RequestData.ReadInt32();

            (ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21();

            LinuxError errno  = LinuxError.EBADF;
            ISocket    socket = _context.RetrieveSocket(socketFd);

            if (socket != null)
            {
                IPEndPoint endPoint = context.Memory.Read <BsdSockAddr>(bufferPosition).ToIPEndPoint();

                errno = socket.Bind(endPoint);
            }

            return(WriteBsdResult(context, 0, errno));
        }
Exemple #12
0
 private void Listen(int port)
 {
     _client.Bind(new IPEndPoint(IPAddress.Any, port));
     while (_isListening)
     {
         if (_client.Available <= 0)
         {
             continue;
         }
         var        start    = DateTime.Now.Ticks;
         IPEndPoint endPoint = null;
         var        buffer   = _client.Receive(ref endPoint);
         if (buffer == null)
         {
             continue;
         }
         if (buffer.Length == 0)
         {
             continue;
         }
         var ds = DataStorage.CreateForRead(buffer);
         while (!ds.Empty)
         {
             int        len = ds.ReadInt32();
             var        msg = Message.Deserialize(ds.ReadBytes(len));
             Connection connection;
             if (!_connectionManager.TryGetConnection(out connection, msg, endPoint))
             {
                 continue;
             }
             if (AllowedTokens.IsAccepted(connection.Token))
             {
                 ProcessDatagram(msg, connection);
             }
             else
             {
                 ForceDisconnect(connection);
             }
         }
         var end = DateTime.Now.Ticks;
     }
 }
Exemple #13
0
        public void Listen(EndPoint localEndPoint)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (!CanListen((IPEndPoint)localEndPoint))
            {
                throw new InvalidOperationException("Can not start a server that was previously disposed!");
            }

            _listenerSocket = new TcpSocket(localEndPoint.AddressFamily);
            _listenerSocket.Bind(localEndPoint);
            _listenerSocket.Listen(5000);

            _listenerTask = AcceptClientAsync();

            _log.Info($"Listening for connections on {localEndPoint}");
        }
 private void Open(EndPoint localEndPoint, int pendingConnections)
 {
     try
     {
         handle = SocketFactory.CreateNonBlockingTcpSocket();
         IPEndPoint ipep = (IPEndPoint)localEndPoint;
         handle.UserSocket.ExclusiveAddressUse = false;
         handle.Bind(ipep);
         handle.Listen(pendingConnections);
         this.reactor.RegisterHandler(this, EventType.ACCEPT_EVENT);
         log.Info("Acceptor listening on {0} : {1}", ipep.Address.ToString(), ipep.Port.ToString());
     }
     catch (ObjectDisposedException ex)
     {
         log.Warn(ex, "Acceptor Socket has been disposed");
     }
     catch (SocketException ex)
     {
         log.Error(ex, String.Format("Acceptor failed to bind to local endpoint. WSAError - {0}",
                                     ex.SocketErrorCode.ToString()));
         Dispose();
     }
 }
Exemple #15
0
 public int Bind()
 {
     _ServerSocket.Bind();
     return(1); //success, if logic to check for failed listen, return zero. future
 }
Exemple #16
0
 public void Launch()
 {
     m_Socket.Bind(Port: 0);
     m_Enable = true;
     ThreadPool.QueueUserWorkItem(Run, state: null);
 }
Exemple #17
0
        /// <summary>
        /// Implements communication logic in client mode.
        /// </summary>
        private void ClientThread()
        {
            // Instantiates RudpInternalSocket if null and binds the actual socket
            if (_socket == null)
            {
                _socket = new RudpInternalSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            }

            _socket.Bind(new IPEndPoint(IPAddress.Any, RemoteEndpoint.Port));

            // Sends connection request for client mode.
            _socket.Send(
                Packet.ToBytes(new Packet()
            {
                AppId             = AppId,
                SequenceNumber    = _nextSeqNumber++,
                AckSequenceNumber = 0,
                AckBitfield       = new Bitfield(4),
                Type = PacketType.ConnectionRequest,
            }),
                RemoteEndpoint);

            IsActive = true;

            // Starts connection request timeout countdown
            _timeoutStopwatch = new Stopwatch();
            _timeoutStopwatch.Start();

            _rttStopwatch.Start();

            byte[] receiveBuffer = new byte[4096];

            // Connection handling main loop in client mode.
            while (IsActive)
            {
                if (_timeoutStopwatch.ElapsedMilliseconds > 500)
                {
                    IsActive = false;
                    State    = ClientState.Disconnected;
                }

                // Executes receive update
                if (_socket.Available > 0)
                {
                    EndPoint endPoint     = new IPEndPoint(IPAddress.Any, 0);
                    var      receiveCount = _socket.Receive(receiveBuffer, 0, receiveBuffer.Length, ref endPoint);

                    if (endPoint.Equals(RemoteEndpoint))
                    {
                        ReceiveUpdate(Packet.FromBytes(receiveBuffer, 0, receiveCount));
                    }
                }

                if (State == ClientState.Connected)
                {
                    lock (SendStopwatch)
                    {
                        // Executes send update based on the send rate.
                        if (SendStopwatch.ElapsedMilliseconds >= 1000 / SendRate)
                        {
                            SendStopwatch.Restart();
                            var packet = SendUpdate();
                            _socket.Send(Packet.ToBytes(packet), RemoteEndpoint);
                        }
                    }
                }

                Thread.Yield();
            }

            // Closes the connection and releases the socket.
            SendStopwatch?.Stop();
            _timeoutStopwatch?.Stop();
            State = ClientState.Disconnected;
            Close();
        }
Exemple #18
0
 public void Bind(IPEndPoint from)
 {
     _socket.Bind(from);
 }
Exemple #19
0
 public void Bind(EndPoint endPoint)
 {
     socket.Bind(endPoint);
     active = true;
 }
Exemple #20
0
 private void Bind(IPAddress ipAddress, int port)
 {
     SafeExecution.TryCatch(() => _sListener.Bind(ipAddress, port),
                            ExceptionHandler);
 }