Пример #1
0
        private void AcceptCallback(IAsyncResult ar)
        {
            m_server = m_listener.EndAccept(ar);
            m_server.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.None, ReceiveCallback, null);

            ClientConnected.Fire(this, EventArgs.Empty);
        }
Пример #2
0
        public Promise OpenForNewConnections()
        {
            isListening       = true;
            listeningDeferred = Deferred.Create();
            var startListeningDeferred = Deferred.Create();
            BackgroundThread t         = null;

            t = new BackgroundThread(() =>
            {
                try
                {
                    listener = new TcpListener(IPAddress.Any, port);
                    listener.Start();
                }
                catch (Exception ex)
                {
                    startListeningDeferred.Reject(ex);
                    return;
                }

                // we have started listening
                startListeningDeferred.Resolve();

                try
                {
                    while (isListening && t.IsExpired == false)
                    {
                        Socket socket;
                        try
                        {
                            socket = listener.AcceptSocket(TimeSpan.FromSeconds(1));
                            if (t.IsExpired)
                            {
                                return;
                            }
                        }
                        catch (TimeoutException)
                        {
                            continue;
                        }
                        var connection = new RemoteSocketConnection()
                        {
                            ClientId        = (socket.RemoteEndPoint as IPEndPoint).Address.ToString() + ":" + (socket.RemoteEndPoint as IPEndPoint).Port,
                            RemoteSocket    = socket,
                            MessageReceived = this.MessageReceived,
                        };
                        this.OnDisposed(connection.Dispose);
                        connection.Listen();
                        connections.Add(connection.ClientId, connection);
                        ClientConnected.Fire(connection);
                    }
                    listener.Stop();
                    listeningDeferred.Resolve();
                }
                catch (Exception ex)
                {
                    listeningDeferred.Reject(ex);
                }
                finally
                {
                    listeningDeferred = null;
                }
            });
            this.OnDisposed(t.Dispose);
            t.Start();
            return(startListeningDeferred.Promise);
        }