Ejemplo n.º 1
0
        public void Listen()
        {
            if (IsListening || Listener != null)
            {
                throw new InvalidOperationException();
            }

            IsListening = true;
            Listener    = new TcpListener(IPAddress.Any, Port);
            Listener.Start();

            if (Listening != null)
            {
                Listening(this, new EventArgs());
            }

            while (IsListening)
            {
                TcpClient client;

                try
                {
                    client = Listener.AcceptTcpClient();
                }
                catch (SocketException)
                {
                    continue;
                }

                var context = ClientContext.FromClient(client);

                ThreadHelper.DoBackground(() =>
                {
                    using (client)
                    {
                        HandleClient(context);
                    }
                });
            }
        }
Ejemplo n.º 2
0
        public void Connect(string hostname)
        {
            if (IsConnected)
            {
                throw new InvalidOperationException();
            }

            do
            {
                var c = new TcpClient();
                InvokeConnecting(c);

                try
                {
                    c.Connect(hostname, Port);
                    Context = ClientContext.FromClient(c);
                    Context.AcquireWriteLock();
                    Context.AcquireReadLock();

                    try
                    {
                        Context.Writer.WriteHello();
                        InvokeHelloSent(Context.Client);
                        Context.Reader.ReadHello();
                    }
                    finally
                    {
                        Context.ReleaseWriteLock();
                        Context.ReleaseReadLock();
                    }

                    InvokeHelloReceived(Context.Client);
                    ReadThread  = CreateReadThread();
                    IsConnected = true;
                }
                catch (Exception e)
                {
                    if (ConnectFailed != null)
                    {
                        ConnectFailed(this, new ItemEventArgs <Exception>(e));
                    }

                    try
                    {
                        c.Client.Dispose();
                    }
                    catch { }

                    try
                    {
                        c.Client.Shutdown(SocketShutdown.Both);
                    }
                    catch { }

                    try
                    {
                        c.Close();
                    }
                    catch { }

                    Thread.Sleep(1000);
                }
            } while (!IsConnected);

            InvokeConnected(Context.Client);
        }