Exemplo n.º 1
0
        private void ConnectComplete(object sender, SocketAsyncEventArgs args)
        {
            if (args.SocketError != SocketError.Success)
            {
                logger.Error($"Service protocol client {id}: Could not connect to server! Remote end point: {args.RemoteEndPoint} Reason: {args.SocketError}");

                args.Dispose();

                DisconnectLogic();

                return;
            }

            args.Dispose();

            Thread.MemoryBarrier();

            connected = true;

            lastConnectionActiveTime = Environment.TickCount;

            Task.Run(() =>
            {
                if (!socket.ReceiveAsync(receiveArgs))
                {
                    Receive(null, receiveArgs);
                }
            });
        }
Exemplo n.º 2
0
        public bool Listen(ushort port, uint backlog = 32)
        {
            lock (lockObject)
            {
                try
                {
                    if (listenSocket != null)
                    {
                        throw new Exception($"{nameof(Listen)} already in progress!");
                    }

                    connectionVersion++;

                    listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));

                    listenSocket.NoDelay = false;

                    listenSocket.Listen((int)backlog);

                    var acceptArgs = new SocketAsyncEventArgs();
                    acceptArgs.Completed += Accept;

                    if (!listenSocket.AcceptAsync(acceptArgs))
                    {
                        Accept(listenSocket, acceptArgs);
                    }

                    return(true);
                }
                catch (Exception e)
                {
                    listenSocket = null;

                    logger.Error($"Service protocol server: Could not start listen! Details: {e}");
                }
            }

            return(false);
        }