Ejemplo n.º 1
0
 private void Form1_Load(object sender, EventArgs e)
 {
     _socket = new AsyncSocket();
     _socket.CouldNotConnect    += _socket_CouldNotConnect;
     _socket.SocketConnected    += _socket_SocketConnected;
     _socket.SocketDataArrival  += _socket_SocketDataArrival;
     _socket.SocketDisconnected += _socket_SocketDisconnected;
     _socket.SocketError        += _socket_SocketError;
 }
Ejemplo n.º 2
0
        public void RemoveSocket(AsyncSocket socket)
        {
            AdjustLoad(-1);

            var item = m_sockets[socket];

            m_sockets.Remove(socket);
            item.Cancelled = true;
        }
Ejemplo n.º 3
0
 // 소켓연결이 해제되었습니다.
 public void NotifyReleaseSocket(ASSOCKDESC sockdesc, AsyncSocket socket)
 {
     Console.WriteLine(sockdesc.ManagedID + " Disconnected");
     lock (this)
     {
         theSessions.Remove(sockdesc.ManagedID);
     }
     sockdesc.NetSender.ReleaseASSOCKDESC(sockdesc);
 }
Ejemplo n.º 4
0
        public PgmSession([NotNull] PgmSocket pgmSocket, [NotNull] Options options)
        {
            m_handle  = pgmSocket.Handle;
            m_options = options;
            m_data    = new byte[Config.PgmMaxTPDU];
            m_joined  = false;

            m_state = State.Idle;
        }
Ejemplo n.º 5
0
            public override void OnSocketDisposed(AsyncSocket so)
            {
                var connector = so.Connector as ConnectorEx;

                Agent.TryClearLeader(connector, so);
                base.OnSocketDisposed(so);
                connector.IsAutoReconnect = true;
                connector.TryReconnect();
            }
Ejemplo n.º 6
0
        public void RemoteEndPoint()
        {
            CompletionPort completionPort = CompletionPort.Create();

            var listenSocket = AsyncSocket.CreateIPv4Tcp();

            completionPort.AssociateSocket(listenSocket, null);
            listenSocket.Bind(IPAddress.Any, 0);
            int port = listenSocket.LocalEndPoint.Port;

            listenSocket.Listen(1);

            listenSocket.Accept();

            var clientSocket = AsyncSocket.CreateIPv4Tcp();

            completionPort.AssociateSocket(clientSocket, null);
            clientSocket.Bind(IPAddress.Any, 0);
            clientSocket.Connect("localhost", port);

            CompletionStatus completionStatus;

            bool accepted  = false;
            bool connected = false;

            while (!accepted || !connected)
            {
                completionPort.GetQueuedCompletionStatus(-1, out completionStatus);

                if (completionStatus.AsyncSocket == clientSocket && !connected)
                {
                    Assert.AreEqual(OperationType.Connect, completionStatus.OperationType);
                    Assert.AreEqual(SocketError.Success, completionStatus.SocketError);
                    connected = true;
                }
                else if (completionStatus.AsyncSocket == listenSocket && !accepted)
                {
                    Assert.AreEqual(OperationType.Accept, completionStatus.OperationType);
                    Assert.AreEqual(SocketError.Success, completionStatus.SocketError);
                    accepted = true;
                }
                else
                {
                    Assert.Fail();
                }
            }

            var server = listenSocket.GetAcceptedSocket();

            Assert.AreEqual(clientSocket.LocalEndPoint, server.RemoteEndPoint);
            Assert.AreEqual(clientSocket.RemoteEndPoint, server.LocalEndPoint);

            completionPort.Dispose();
            listenSocket.Dispose();
            server.Dispose();
            clientSocket.Dispose();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GNTPWebSocketReader"/> class.
        /// </summary>
        /// <param name="socket">The <see cref="AsyncSocket"/></param>
        /// <param name="passwordManager">The <see cref="PasswordManager"/> containing a list of allowed passwords</param>
        /// <param name="passwordRequired">Indicates if a password is required</param>
        /// <param name="allowNetworkNotifications">Indicates if network requests are allowed</param>
        /// <param name="allowBrowserConnections">Indicates if browser requests are allowed</param>
        /// <param name="allowSubscriptions">Indicates if SUBSCRIPTION requests are allowed</param>
        /// <param name="requestInfo">The <see cref="RequestInfo"/> associated with this request</param>
        public GNTPWebSocketReader(AsyncSocket socket, PasswordManager passwordManager, bool passwordRequired, bool allowNetworkNotifications, bool allowBrowserConnections, bool allowSubscriptions, RequestInfo requestInfo)
            : base(socket, passwordManager, passwordRequired, allowNetworkNotifications, allowBrowserConnections, allowSubscriptions, requestInfo)
        {
            this.allowed = allowBrowserConnections;

            parser = new GNTPParser2(passwordManager, passwordRequired, allowNetworkNotifications, allowBrowserConnections, allowSubscriptions, requestInfo);
            parser.MessageParsed += new GNTPParser2.GNTPParserMessageParsedEventHandler(parser_MessageParsed);
            parser.Error         += new GNTPParser2.GNTPParserErrorEventHandler(parser_Error);
        }
Ejemplo n.º 8
0
        public void EventDisconnected(String addr, AsyncSocket ch)
        {
            if ((m_monitorEvents & SocketEvent.Disconnected) == 0)
            {
                return;
            }

            MonitorEvent(new MonitorEvent(SocketEvent.Disconnected, addr, ch));
        }
Ejemplo n.º 9
0
        public void EventListening(String addr, AsyncSocket ch)
        {
            if ((m_monitorEvents & SocketEvent.Listening) == 0)
            {
                return;
            }

            MonitorEvent(new MonitorEvent(SocketEvent.Listening, addr, ch));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GNTPSocketReader"/> class.
        /// </summary>
        /// <param name="socket">The <see cref="AsyncSocket"/></param>
        /// <param name="passwordManager">The <see cref="PasswordManager"/> containing a list of allowed passwords</param>
        /// <param name="passwordRequired">Indicates if a password is required</param>
        /// <param name="allowNetworkNotifications">Indicates if network requests are allowed</param>
        /// <param name="allowBrowserConnections">Indicates if browser requests are allowed</param>
        /// <param name="allowSubscriptions">Indicates if SUBSCRIPTION requests are allowed</param>
        /// <param name="requestInfo">The <see cref="RequestInfo"/> associated with this request</param>
        public GNTPSocketReader(AsyncSocket socket, PasswordManager passwordManager, bool passwordRequired, bool allowNetworkNotifications, bool allowBrowserConnections, bool allowSubscriptions, RequestInfo requestInfo)
        {
            this.parser           = new GNTPParser(passwordManager, passwordRequired, allowNetworkNotifications, allowBrowserConnections, allowSubscriptions, requestInfo);
            parser.Error         += new GNTPParser.GNTPParserErrorEventHandler(parser_Error);
            parser.MessageParsed += new GNTPParser.GNTPParserMessageParsedEventHandler(parser_MessageParsed);

            this.socket     = socket;
            this.socket.Tag = parser;
        }
Ejemplo n.º 11
0
        public void AddSocket(AsyncSocket socket, IProactorEvents proactorEvents)
        {
            var item = new Item(proactorEvents);

            m_sockets.Add(socket, item);

            m_completionPort.AssociateSocket(socket, item);
            AdjustLoad(1);
        }
Ejemplo n.º 12
0
        public static void ReceiveData(AsyncSocket socket)
        {
            string ip_port = NetUtil.ToIportString(socket.RemoteEndPoint);

            lock (m_lock)
            {
                m_ip_port_sockets[ip_port] = socket;
            }
            ReceiveData(ip_port);
        }
Ejemplo n.º 13
0
        public ClientThreadT(AsyncSocket clientSocket, SelItem clientItem, String name)
        {
            m_clientSocket = clientSocket;
            m_clientItem   = clientItem;
            m_name         = name;

            m_thread = new Thread(thread_fun);
            m_thread.IsBackground = true;
            m_thread.Start();
        }
        /// <summary>
        /// Handles the socket's DidWrite event.
        /// Calls the callback.
        /// </summary>
        /// <param name="sender">The <see cref="AsyncSocket"/>.</param>
        /// <param name="tag">The tag identifying the write request.</param>
        void socket_DidWrite(AsyncSocket sender, long tag)
        {
            // remove this since we dont need it any more
            sender.DidWrite -= new AsyncSocket.SocketDidWrite(socket_DidWrite);

            if (tag == HANDSHAKE_RESPONSE_TAG)
            {
                this.callback.BeginInvoke(null, null);
            }
        }
Ejemplo n.º 15
0
        public PgmSession(PgmSocket pgmSocket, Options options)
        {
            m_handle    = pgmSocket.Handle;
            m_pgmSocket = pgmSocket;
            m_options   = options;
            data        = new byte[Config.PgmMaxTPDU];
            m_joined    = false;

            m_state = State.Idle;
        }
Ejemplo n.º 16
0
        private void asyncSocket_DidClose(AsyncSocket sender)
        {
            LogInfo("Disconnected from host");

            asyncSocket = null;
            CreateAndSetupAsyncSocket();

            fetchButton.Enabled = true;
            sslCheckBox.Enabled = true;
        }
Ejemplo n.º 17
0
        /// <summary>

        /// Releases unmanaged and - optionally - managed resources

        /// </summary>

        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>

        protected void Dispose(bool disposing)

        {
            if (disposing)

            {
                try

                {
                    Stop();



                    if (this.listenSocket != null)

                    {
                        this.listenSocket.DidAccept -= new AsyncSocket.SocketDidAccept(listenSocket_DidAccept);

                        this.listenSocket = null;
                    }



                    if (this.socketCleanupTimer != null)

                    {
                        this.socketCleanupTimer.Elapsed -= new System.Timers.ElapsedEventHandler(socketCleanupTimer_Elapsed);

                        this.socketCleanupTimer.Close();

                        this.socketCleanupTimer.Dispose();

                        this.socketCleanupTimer = null;
                    }



                    if (this.bonjour != null)

                    {
                        this.bonjour.Stop();

                        this.bonjour.Dispose();

                        this.bonjour = null;
                    }
                }

                catch

                {
                    // suppress
                }
            }
        }
Ejemplo n.º 18
0
        private void asyncSocket_DidClose(AsyncSocket sender)
        {
#if IS_MULTITHREADED
            lock (connectedSockets)
            {
                connectedSockets.Remove(sender);
            }
#else
            connectedSockets.Remove(sender);
#endif
        }
Ejemplo n.º 19
0
        /// <summary>

        /// Checks to see if any open sockets have disconnected and cleans them up.

        /// </summary>

        /// <param name="sender">The sender</param>

        /// <param name="e">Event args</param>

        void socketCleanupTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

        {
            this.socketCleanupTimer.Stop();

            int count = this.connectedSockets.Count;

            if (count > 0)

            {
                Queue <AsyncSocket> queue = new Queue <AsyncSocket>(this.connectedSockets.Count);

                lock (syncLock)

                {
                    foreach (ConnectedSocket cs in this.connectedSockets)

                    {
                        queue.Enqueue(cs.Socket);
                    }
                }



                while (queue.Count > 0)

                {
                    AsyncSocket socket = queue.Dequeue();

                    if (socket != null)

                    {
                        if (this.connectedSockets.Contains(socket))

                        {
                            bool safeToDisconnect = this.connectedSockets[socket].SafeToDisconnect;

                            if (safeToDisconnect && !socket.SmartConnected)

                            {
                                // socket is disconnected from the other end

                                socket.Close();
                            }
                        }
                    }
                }
            }

            if (this.isStarted)
            {
                this.socketCleanupTimer.Start();
            }
        }
Ejemplo n.º 20
0
        public override void OnSocketConnectError(AsyncSocket so, Exception e)
        {
            base.OnSocketConnectError(so, e);
            var agent = so.UserState as GlobalAgent.Agent;

            if (null == e)
            {
                e = new Exception("Normal Connect Error???"); // ConnectError 应该 e != null 吧,懒得确认了。
            }
            agent.Logined.TrySetException(e);
        }
Ejemplo n.º 21
0
        public override void OnHandshakeDone(AsyncSocket so)
        {
            base.OnHandshakeDone(so);
            var agent = so.UserState as GlobalAgent.Agent;

            if (agent.LoginedTimes.Get() > 1)
            {
                var relogin = new GlobalCacheManager.ReLogin();
                relogin.Argument.AutoKeyLocalId = Zeze.Config.AutoKeyLocalId;
                relogin.Argument.GlobalCacheManagerHashIndex = agent.GlobalCacheManagerHashIndex;
                relogin.Send(so,
                             (_) =>
                {
                    if (relogin.IsTimeout)
                    {
                        agent.Logined.TrySetException(new Exception("GloalAgent.ReLogin Timeout"));;
                    }
                    else if (relogin.ResultCode != 0)
                    {
                        agent.Logined.TrySetException(new Exception($"GlobalAgent.ReLogoin Error {relogin.ResultCode}"));
                    }
                    else
                    {
                        agent.LoginedTimes.IncrementAndGet();
                        agent.Logined.SetResult(so);
                    }
                    return(0);
                });
            }
            else
            {
                var login = new GlobalCacheManager.Login();
                login.Argument.AutoKeyLocalId = Zeze.Config.AutoKeyLocalId;
                login.Argument.GlobalCacheManagerHashIndex = agent.GlobalCacheManagerHashIndex;
                login.Send(so,
                           (_) =>
                {
                    if (login.IsTimeout)
                    {
                        agent.Logined.TrySetException(new Exception("GloalAgent.Login Timeout"));;
                    }
                    else if (login.ResultCode != 0)
                    {
                        agent.Logined.TrySetException(new Exception($"GlobalAgent.Logoin Error {login.ResultCode}"));
                    }
                    else
                    {
                        agent.LoginedTimes.IncrementAndGet();
                        agent.Logined.SetResult(so);
                    }
                    return(0);
                });
            }
        }
Ejemplo n.º 22
0
        static ProtocolState()
        {
            Settings = new XmppSettings();
            Events   = new XmppEvents();
            Socket   = new AsyncSocket();

            State                = new DisconnectedState();
            Events.OnNewTag     += EventsOnOnNewTag;
            Events.OnConnect    += EventsOnOnConnect;
            Events.OnDisconnect += EventsOnOnDisconnect;
        }
Ejemplo n.º 23
0
        // 소켓연결이 해제되었습니다.
        public void OnReleaseSocket(AsyncSocketContext sockdesc, AsyncSocket socket)
        {
            Console.WriteLine(sockdesc.ManagedID + " Disconnected");

            lock (this)
            {
                theSessions.Remove(sockdesc.ManagedID);
            }

            sockdesc.NetSender.ReleaseAsyncSocketContext(sockdesc);
        }
Ejemplo n.º 24
0
        public override void OnSocketClose(AsyncSocket so, Exception e)
        {
            base.OnSocketClose(so, e);
            var agent = so.UserState as GlobalAgent.Agent;

            if (null == e)
            {
                e = new Exception("Peer Normal Close.");
            }
            agent.OnSocketClose(this, e);
        }
Ejemplo n.º 25
0
        void ISocketEventListener.OnConnect(BaseSocket sock)
        {
#if !NO_SSL
            if ((bool)m_listener[Options.SSL])
            {
                AsyncSocket s = sock as AsyncSocket;
                m_listener[Options.REMOTE_CERTIFICATE] = s.RemoteCertificate;
            }
#endif
            m_listener.Connected();
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Listens for an inbound connection.
        /// </summary>
        public override void Accept()
        {
            AsyncSocket s = new AsyncSocket(null, this, (bool)m_listener[Options.SSL], false);

            s.LocalCertificate = m_listener[Options.LOCAL_CERTIFICATE] as
                                 System.Security.Cryptography.X509Certificates.X509Certificate2;

            m_sock = s;
            m_sock.Accept(new Address((int)m_listener[Options.PORT]));
            m_sock.RequestAccept();
        }
Ejemplo n.º 27
0
        public void EnhancedSocket_Async_SendRecv()
        {
            AsyncSocket sockListen = null;
            AsyncSocket sock1      = null;
            AsyncSocket sock2      = null;
            int         cb;

            try
            {
                sockListen = new AsyncSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sockListen.ListenOn(new IPEndPoint(IPAddress.Any, 45001));

                sock1 = new AsyncSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock1.Connect(new IPEndPoint(IPAddress.Loopback, 45001));

                sock2 = sockListen.Accept();

                for (int i = 0; i < 1000; i++)
                {
                    byte[] buf10 = new byte[10];
                    byte[] buf5  = new byte[5];

                    sock1.Send(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    cb = sock2.Receive(buf10);
                    Assert.AreEqual(10, cb);
                    CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, buf10);

                    sock2.Send(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    cb = sock1.Receive(buf5);
                    Assert.AreEqual(5, cb);
                    CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, buf5);
                    cb = sock1.Receive(buf5);
                    Assert.AreEqual(5, cb);
                    CollectionAssert.AreEqual(new byte[] { 5, 6, 7, 8, 9 }, buf5);
                }
            }
            finally
            {
                if (sockListen != null)
                {
                    sockListen.Close();
                }

                if (sock1 != null)
                {
                    sock1.Close();
                }

                if (sock2 != null)
                {
                    sock2.Close();
                }
            }
        }
Ejemplo n.º 28
0
        private void asyncSocket_DidReadPartial(AsyncSocket sender, int partialLength, long tag)
        {
            if (tag == HTTP_BODY)
            {
                totalBytesReceived += partialLength;

                float percentComplete = (float)totalBytesReceived / (float)fileSizeInBytes;

                progressBar.Value = (int)(percentComplete * 100);
            }
        }
Ejemplo n.º 29
0
        private void Server()
        {
            SocketWatcher s_w = new SocketWatcher(20);

            //s_w.RequireClientCert = true;

            X509Certificate2 c2;
            X509Store        store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);
            X509Certificate2Collection cert = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", true);

            if (cert.Count == 0)
            {
                c2 = new X509Certificate2("../../localhost-cert.p12", "test");
                store.Add(c2);
            }
            else
            {
                c2 = cert[0];
            }
            Assert.IsTrue(c2.HasPrivateKey);
            Assert.IsNotNull(c2.PrivateKey);
            Assert.AreEqual(typeof(X509Certificate2), c2.GetType());

            cert = store.Certificates.Find(X509FindType.FindByThumbprint, c2.GetCertHashString(), false);
            c2   = cert[0];
            Assert.AreEqual(typeof(X509Certificate2), c2.GetType());
            Assert.IsTrue(c2.HasPrivateKey);
            Assert.IsNotNull(c2.PrivateKey);
            store.Close();
            s_w.LocalCertificate = c2;
            s_w.Synchronous      = true;

            m_listen = s_w.CreateListenSocket(this, a, true);
            lock (start)
            {
                Monitor.Pulse(start);
            }

            try
            {
                m_listen.RequestAccept();
            }
            catch (Exception ex)
            {
                lock (done)
                {
                    succeeded    = false;
                    errorMessage = ex.Message;
                    Monitor.Pulse(done);
                }
            }
        }
Ejemplo n.º 30
0
        public void Disconnect()
        {
            Connected     = false;
            Authenticated = false;

            if (socket != null)
            {
                socket.Close();
                socket = null;
            }
        }
Ejemplo n.º 31
0
    public async Task<bool> Connect(string host)
    {
        IPHostEntry hostEntry = null;
        hostEntry = Dns.GetHostEntry(host);

        foreach (IPAddress address in hostEntry.AddressList)
        {
            IPEndPoint ipe = new IPEndPoint(address, 6667);
            AsyncSocket temp = new AsyncSocket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Unspecified);
            await temp.ConnectTaskAsync(ipe);

            if (temp.Connected)
            {
                s = temp;
                break;
            }
        }
        return s.Connected;
    }
Ejemplo n.º 32
0
        public override void AssociateSocket(AsyncSocket socket, object state)
        {
            if (!(socket is Windows.Socket))
            {
                throw new ArgumentException("socket must be of type Windows.Socket", "socket");
            }

            Socket windowsSocket = socket as Socket;

            if (windowsSocket.CompletionPort != this)
            {
                IntPtr result = UnsafeMethods.CreateIoCompletionPort(windowsSocket.Handle, m_completionPortHandle,
                  SocketCompletionKey, 0);

                if (result == InvalidCompletionPort || result == InvalidCompletionPortMinusOne)
                {
                    throw new Win32Exception();
                }
            }

            windowsSocket.SetCompletionPort(this, state);
        }
Ejemplo n.º 33
0
 public void EngageWith(AsyncSocket.ISocket socket)
 {
     _pipeline.EngageWith(socket);
 }
Ejemplo n.º 34
0
 private void _listenSocket_ConnectionAccept(AsyncSocket tempSocket)
 {
     try {
         _clientSocket.PassSocket(lStatus.GetObject(lStatus.ActiveIndex).sWindow) = tempSocket;
     } catch (Exception ex) {
         throw ex;
     }
 }
Ejemplo n.º 35
0
        public override void Accept(AsyncSocket socket)
        {
            if (m_acceptSocketBufferAddress == IntPtr.Zero)
            {
                m_acceptSocketBufferSize = (m_boundAddress.Size + 16) * 2;

                m_acceptSocketBufferAddress = Marshal.AllocHGlobal(m_acceptSocketBufferSize);
            }

            int bytesReceived;

            m_acceptSocket = socket as Windows.Socket;

            m_inOverlapped.StartOperation(OperationType.Accept);

            if (!m_acceptEx(Handle, m_acceptSocket.Handle, m_acceptSocketBufferAddress, 0,
                  m_acceptSocketBufferSize / 2,
                  m_acceptSocketBufferSize / 2, out bytesReceived, m_inOverlapped.Address))
            {
                var socketError = (SocketError)Marshal.GetLastWin32Error();

                if (socketError != SocketError.IOPending)
                {
                    throw new SocketException((int)socketError);
                }
            }
            else
            {
                CompletionPort.PostCompletionStatus(m_inOverlapped.Address);
            }
        }
Ejemplo n.º 36
0
        public override void Accept(AsyncSocket socket)
        {
            NativeSocket nativeSocket = (NativeSocket)socket;

            m_inSocketAsyncEventArgs.AcceptSocket = nativeSocket.m_socket;

            if (!m_socket.AcceptAsync(m_inSocketAsyncEventArgs))
            {
                CompletionStatus completionStatus = new CompletionStatus(this, m_state, OperationType.Accept, SocketError.Success, 0);

                m_completionPort.Queue(ref completionStatus);
            }
        }
Ejemplo n.º 37
0
 public void NewSocket(int id, Form form)
 {
     try {
         socket = new AsyncSocket();
         statusId = id;
         _invoke = new Form();
         _invoke = form;
     } catch (Exception ex) {
         throw ex;
     }
 }