Example #1
0
        public void Connect(string clientName, ConnectCallback cb)
        {
            connect_callback_ = cb;
            if (current_status == ConnectStatus.Connecting || current_status == ConnectStatus.Connected)
            {
                return;
            }
            string        error       = null;
            LNReq_Connect connectData = null;

            try {
                LNReq_Connect.Builder connectBuilder = LNReq_Connect.CreateBuilder();
                connectBuilder.SetClientName(clientName);
                connectData = connectBuilder.Build();
            }
            catch (Exception e) {
                error = e.Message;
            }
            if (null != error)
            {
                cb(false, error);
                return;
            }
            if (!channel_.Send(connectData))
            {
                cb(false, "unknown");
            }
            else
            {
                current_status = ConnectStatus.Connecting;
                //connectOpt_timeout_.Add(session, cb, () => cb(false, "connect request timeout"));
            }
        }
Example #2
0
    void Initialize()
    {
        if (!isInitialized)
        {
                        #pragma warning disable CS0162
            if (isLogging)
            {
                Debug.Log(TAG + "Initialize");
            }
                        #pragma warning restore CS0162
                        #if UNITY_ANDROID && !UNITY_EDITOR
            AndroidJavaClass  jcUnityPlayer   = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = jcUnityPlayer.GetStatic <AndroidJavaObject>("currentActivity");

            AndroidJavaClass jcMds = new AndroidJavaClass("com.movesense.mds.Mds");                     // name of the class not the plugin-file

            var builder = jcMds.CallStatic <AndroidJavaObject>("builder");

            movesensePlugin = builder.Call <AndroidJavaObject>("build", currentActivity);
                        #elif UNITY_IOS && !UNITY_EDITOR
            callbackObject = new ConnectCallback();

            InitMDS(onConnect, onConnectionComplete, onConnectError, onDisconnect);
                        #elif UNITY_STANDALONE_OSX || UNITY_EDITOR
                        #endif

            isInitialized = true;
                        #pragma warning disable CS0162
            if (isLogging)
            {
                Debug.Log(TAG + "Mds initialized");
            }
                        #pragma warning restore CS0162
        }
    }
        static int _m_Connect(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                WsGame __cl_gen_to_be_invoked = (WsGame)translator.FastGetCSObj(L, 1);



                {
                    string            url        = LuaAPI.lua_tostring(L, 2);
                    ConnectCallback   callback   = translator.GetDelegate <ConnectCallback>(L, 3);
                    OnMessageCallback msgHandler = translator.GetDelegate <OnMessageCallback>(L, 4);

                    __cl_gen_to_be_invoked.Connect(url, callback, msgHandler);



                    return(0);
                }
            } catch (System.Exception __gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + __gen_e));
            }
        }
Example #4
0
        public void Create(IReadOnlyList <Endpoint> endpts, bool hasMore, EndpointSelectionType selType,
                           ICreateConnectionCallback callback)
        {
            Debug.Assert(endpts.Count > 0);

            //
            // Apply the overrides.
            //
            IReadOnlyList <Endpoint> endpoints = ApplyOverrides(endpts).ToArray();

            //
            // Try to find a connection to one of the given endpoints.
            //
            try
            {
                Connection?connection = FindConnection(endpoints, out bool compress);
                if (connection != null)
                {
                    callback.SetConnection(connection, compress);
                    return;
                }
            }
            catch (System.Exception ex)
            {
                callback.SetException(ex);
                return;
            }
            var cb = new ConnectCallback(this, hasMore, callback, selType);

            // TODO: do something with the return value task
            _ = cb.GetConnectorsAsync(endpoints);
        }
    public void Connect(ConnectCallback callback)
    {
        ws = new WebSocket(websocketURL);
        var cookie = new Cookie();

        cookie.Name  = "access";
        cookie.Value = PlayerPrefs.GetString("uid");
        ws.SetCookie(cookie);

        ws.OnOpen    += OnOpenHandler;
        ws.OnMessage += OnMessageHandler;
        ws.OnClose   += OnCloseHandler;

        stateMachine.AddHandler(APIState.Running, () => {
            ws.ConnectAsync();
        });

        stateMachine.AddHandler(APIState.Connected, () => {
            stateMachine.Transition(APIState.Subscribing);
        });

        stateMachine.AddHandler(APIState.Subscribing, () => {
            Subscribe();
        });

        stateMachine.AddHandler(APIState.Subscribed, () => {
            callback.Invoke();
        });

        stateMachine.Run();
    }
Example #6
0
 /// <summary>
 /// 运行
 /// </summary>
 /// <typeparam name="TState"></typeparam>
 /// <param name="accept"></param>
 /// <param name="state"></param>
 public void Run <TState>(ConnectCallback <TState> accept, TState state = default(TState))
 {
     if (!disposing)
     {
         listen.BeginAccept(CompleteAccept <TState>, new object[] { accept, state });
     }
 }
Example #7
0
 /// <summary>
 /// Adds a new socket to this thread. Throws an exception if we already have too many sockets.
 /// </summary>
 /// <param name="address">Address to connect to.</param>
 /// <param name="port">Port to connect to.</param>
 /// <param name="cb">A function to be called when the connection succeeds or fails.</param>
 public void AddSocket(string address, int port, ConnectCallback cb)
 {
     if (sockets == null)
     {
         throw new ObjectDisposedException("NetworkThread");
     }
     lock (this)
     {
         if (AvailableSlot() < 1)
         {
             throw new Exception("Out of socket slots in this thread.");
         }
         connectionqueue.Enqueue(new ConnQueueItem(address, port, cb));
         // If the thread is not running, start it.
         if (thread == null || (thread.ThreadState & ThreadState.Unstarted) != 0)
         {
             thread = new Thread(new ThreadStart(SocketThread));
             thread.IsBackground = true;
             thread.Start();
         }
         // Otherwise, if the thread is sleeping, wake it up.
         else if ((thread.ThreadState & ThreadState.WaitSleepJoin) != 0)
         {
             thread.Interrupt();
         }
     }
 }
Example #8
0
        //using Tcp as Connect protocol
        public void Connect(string serverIp, int serverPort,
                            ConnectCallback connectCallback,
                            ConnectCallback connectFailedCallback
                            )
        {
            mConnectCallback       = connectCallback;
            mConnectFailedCallback = connectFailedCallback;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress  address  = IPAddress.Parse(serverIp);
            IPEndPoint endpoint = new IPEndPoint(address, serverPort);

            IAsyncResult result = socket.BeginConnect(endpoint, new AsyncCallback(ConnectedCallback), socket);

            //timeout detecting
            bool success = result.AsyncWaitHandle.WaitOne(mTimeOut, true);

            if (!success)
            {
                //time out occurs
                mConnectFailedCallback?.Invoke();
            }
            else
            {
                StartReceive();
            }
        }
        public void connectTo(string ip, int port, ConnectCallback callback, object userData)
        {
            if (valid())
            {
                throw new InvalidOperationException("Have already connected!");
            }

            if (!(new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip))
            {
                IPHostEntry ipHost = Dns.GetHostEntry(ip);
                ip = ipHost.AddressList[0].ToString();
            }

            _socket = createSocket();

            ConnectState state = new ConnectState();

            state.connectIP        = ip;
            state.connectPort      = port;
            state.connectCB        = callback;
            state.userData         = userData;
            state.socket           = _socket;
            state.networkInterface = this;

            Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ...");
            connected = false;

            // 先注册一个事件回调,该事件在当前线程触发
            Event.registerIn("_onConnectionState", this, "_onConnectionState");

            var v = new AsyncConnectMethod(this._asyncConnect);

            v.BeginInvoke(state, new AsyncCallback(this._asyncConnectCB), state);
        }
Example #10
0
        public void open(ConnectCallback cb, double timeout)
        {
            connect_cb_ = cb;

            //if (secure_)
            //{
            //    ssl_ctx_.add_certificate_authority( boost::asio::buffer(std::string(aws::auth::VeriSignClass3PublicPrimaryG5)));
            //    ssl_ctx_.add_certificate_authority( boost::asio::buffer(std::string(aws::auth::VeriSignClass3PublicPrimary)));
            //    ssl_socket_ = std::make_shared<boost::asio::ssl::stream<TcpSocket>>(*io_service_,ssl_ctx_);
            //    if (verify_cert_)
            //    {
            //    ssl_socket_->set_verify_mode(boost::asio::ssl::verify_peer);
            //    ssl_socket_->set_verify_callback(boost::asio::ssl::rfc2818_verification(endpoint_));
            //    }
            //}
            //else
            //{
            //    tcp_socket_ = new TcpClient(endpoint_, port_);
            //}

            tcp_socket_ = new TcpClient();
            var result = tcp_socket_.BeginConnect(endpoint_, port_, null, null);

            last_use_ = DateTime.Now;
            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout));

            connect_cb_(success, !success ? "" : "Failed to connect.");

            //    resolver_ = std::make_shared<boost::asio::ip::tcp::resolver>(*io_service_);
            //    boost::asio::ip::tcp::resolver::query query(endpoint_, std::to_string(port_));
            //    resolver_->async_resolve(query, [this](auto ec, auto ep) {this->on_resolve(ec, ep);});
        }
        public void connectTo(string ip, int port, ConnectCallback callback, object userData)
        {
            if (valid())
                throw new InvalidOperationException("Have already connected!");

            if (!(new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip))
            {
                IPHostEntry ipHost = Dns.GetHostEntry(ip);
                ip = ipHost.AddressList[0].ToString();
            }

            // Security.PrefetchSocketPolicy(ip, 843);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, KBEngineApp.app.getInitArgs().getRecvBufferSize() * 2);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.SendBuffer, KBEngineApp.app.getInitArgs().getSendBufferSize() * 2);
            _socket.NoDelay = true;
            //_socket.Blocking = false;

            ConnectState state = new ConnectState();
            state.connectIP = ip;
            state.connectPort = port;
            state.connectCB = callback;
            state.userData = userData;
            state.socket = _socket;
            state.networkInterface = this;

            Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ...");

            // 先注册一个事件回调,该事件在当前线程触发
            Event.registerIn("_onConnectStatus", this, "_onConnectStatus");

            var v = new AsyncConnectMethod(this._asyncConnect);
            v.BeginInvoke(state, new AsyncCallback(this._asyncConnectCB), state);
        }
 public void Connect(string hostName, int port, ConnectCallback callback)
 {
     //Set the callback we set in the parameter to our local variable.
     //We could also use the state parameter with BeginConnect so we don't need a variable as well.
     _connectCallback = callback;
     //We will begin an async connect.
     _baseSocket.BeginConnect(hostName, port, connectCallback, null);
 }
Example #13
0
        private void FinishGetConnection(List <ConnectorInfo> connectors,
                                         ConnectorInfo ci,
                                         Connection connection,
                                         ConnectCallback cb)
        {
            var connectionCallbacks = new HashSet <ConnectCallback>();

            if (cb != null)
            {
                connectionCallbacks.Add(cb);
            }

            var callbacks = new HashSet <ConnectCallback>();

            lock (this)
            {
                foreach (ConnectorInfo c in connectors)
                {
                    if (_pending.TryGetValue(c.Connector, out HashSet <ConnectCallback>?s))
                    {
                        foreach (ConnectCallback cc in s)
                        {
                            if (cc.HasConnector(ci))
                            {
                                connectionCallbacks.Add(cc);
                            }
                            else
                            {
                                callbacks.Add(cc);
                            }
                        }
                        _pending.Remove(c.Connector);
                    }
                }

                foreach (ConnectCallback cc in connectionCallbacks)
                {
                    cc.RemoveFromPending();
                    callbacks.Remove(cc);
                }
                foreach (ConnectCallback cc in callbacks)
                {
                    cc.RemoveFromPending();
                }
                System.Threading.Monitor.PulseAll(this);
            }

            bool compress = _communicator.OverrideCompress ?? ci.Endpoint.HasCompressionFlag;

            foreach (ConnectCallback cc in callbacks)
            {
                cc.GetConnection();
            }
            foreach (ConnectCallback cc in connectionCallbacks)
            {
                cc.SetConnection(connection, compress);
            }
        }
        public void TryConnect(IPEndPoint endpoint, ConnectCallback callback)
        {
            _callback       = callback;
            _serverEndpoint = endpoint;

            var tcpThread = new Thread(Connect);

            tcpThread.Start();
        }
Example #15
0
 RemoveFromPending(ConnectCallback cb, List <ConnectorInfo> connectors)
 {
     foreach (ConnectorInfo ci in connectors)
     {
         if (_pending.TryGetValue(ci.Connector, out HashSet <ConnectCallback>?cbs))
         {
             cbs.Remove(cb);
         }
     }
 }
Example #16
0
        public void TryConnect(IPEndPoint endpoint, ConnectCallback callback)
        {
            _connectionCallback = callback;
            _serverEndpoint     = endpoint;

            var tcpThread = new Thread(Connect)
            {
                Name = $"{_mainClient.LogClientId}| SRS Data"
            };

            tcpThread.Start();
        }
        public static IAsyncResult BeginConnect(IPEndPoint dbg_ep, IPEndPoint con_ep, AsyncCallback callback, TextWriter logWriter = null)
        {
            Socket dbg_sock = null;
            Socket con_sock = null;

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

            if (con_ep != null) {
                con_sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }

            ConnectCallback c = new ConnectCallback (ConnectInternal);
            return c.BeginInvoke (dbg_sock, con_sock, dbg_ep, con_ep, logWriter, callback, con_sock ?? dbg_sock);
        }
Example #18
0
 protected override void OnConnected <TState>(ConnectCallback <TState> callback, TState state = default(TState))
 {
     try
     {
         stream = new SslStream(base.Stream, false, CertificateValidation);
         stream.BeginAuthenticateAsClient($"https://{host}", OnAuthenticated <TState>, new object[] { callback, state });
     }
     catch (Exception e)
     {
         Trace.WriteLine($"ssl authenticating failed {e}.");
         callback(this, false, state);
         Interrupte();
     }
 }
Example #19
0
 public void AuthenticateConnection <TState>(X509Certificate certificate, ConnectCallback <TState> callback, TState state)
 {
     try
     {
         stream = new SslStream(base.Stream, false);
         stream.BeginAuthenticateAsServer(certificate, CompleteAuthenticate <TState>, new object[] { callback, state });
     }
     catch (Exception e)
     {
         Trace.WriteLine($"ssl authenticating failed {e}.");
         callback(null, false, state);
         Interrupte();
     }
 }
Example #20
0
 public SocketWrap(
     ConnectCallback ccb,
     ListenCallback lcb,
     ReceiveCallback rcb,
     DisconnectCallback dcb,
     ErrorCallback ecb)
 {
     _ccb = ccb;
     _rcb = rcb;
     _ecb = ecb;
     _lcb = lcb;
     _dcb = dcb;
     _recvBuf = new byte[1024];
 }
Example #21
0
        public void connectTo(string ip, int port, ConnectCallback callback, object userData)
        {
            if (valid())
            {
                throw new InvalidOperationException("Have already connected!");
            }

            if (!(new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip))
            {
                IPHostEntry ipHost = Dns.GetHostEntry(ip);
                ip = ipHost.AddressList[0].ToString();
            }

            // Security.PrefetchSocketPolicy(ip, 843);
            IPAddress[]   hostAddresses = Dns.GetHostAddresses(ip);
            IPAddress[]   outIPs        = hostAddresses;
            AddressFamily addressFamily = AddressFamily.InterNetwork;

            if (Socket.OSSupportsIPv6 && this.IsHaveIpV6Address(hostAddresses, ref outIPs))
            {
                addressFamily = AddressFamily.InterNetworkV6;
            }
            _socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, NetworkInterface.RECV_BUFFER_MAX * 2);

            ConnectState state = new ConnectState();

            state.connectIP        = ip;
            state.connectPort      = port;
            state.connectCB        = callback;
            state.userData         = userData;
            state.socket           = _socket;
            state.networkInterface = this;

            Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ...");

            // 先注册一个事件回调,该事件在当前线程触发
            Event.registerIn("_onConnectStatus", this, "_onConnectStatus");

            try
            {
                _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(connectCB), state);
            }
            catch (Exception e)
            {
                state.error = e.ToString();
                Event.fireIn("_onConnectStatus", new object[] { state });
            }
        }
        public void reset()
        {
            if (valid())
            {
                _socket.Close(0);
            }
            _socket         = null;
            _packetReceiver = null;
            _packetSender   = null;

            _connectIP   = "";
            _connectPort = 0;
            _connectCB   = null;
            _userData    = null;
        }
Example #23
0
        public bool Connect(ConnectCallback callback)
        {
            _connectCallback = callback;
            var ssh = new SSHLoginParameter();

            ssh.Method               = SSHProtocol.SSH2;
            ssh.AuthenticationType   = AuthenticationType.Password;
            ssh.Account              = "cxn2356";
            ssh.PasswordOrPassphrase = "Jumanji123.";
            //--- X11 forwarding settings
            ssh.EnableX11Forwarding = false;
            ssh.X11Forwarding       = null;
            //--- Agent forwarding settings
            ssh.EnableAgentForwarding          = false;
            ssh.AgentForwardingAuthKeyProvider = null;
            // -- tcp
            var tcp = (ITCPParameter)ssh.GetAdapter(typeof(ITCPParameter));

            tcp.Destination = "10.93.1.255";
            tcp.Port        = 22;
            //--- Log settings
            ISimpleLogSettings logSettings = TerminalSessionsPlugin.Instance.TerminalEmulatorService.CreateDefaultSimpleLogSettings();

            logSettings.LogType = Poderosa.ConnectionParam.LogType.None;
            if (logSettings.LogType != Poderosa.ConnectionParam.LogType.None)
            {
                logSettings.LogPath   = Path.GetTempFileName();
                logSettings.LogAppend = true;
            }
            // -- terminal settings
            _terminalSettings = TerminalSessionsPlugin.Instance.TerminalEmulatorService.CreateDefaultTerminalSettings("Terminal", null);
            _terminalSettings.BeginUpdate();
            _terminalSettings.EnabledCharTriggerIntelliSense = false;
            _terminalSettings.Encoding     = Poderosa.ConnectionParam.EncodingType.UTF8;
            _terminalSettings.LocalEcho    = false;
            _terminalSettings.TransmitNL   = Poderosa.ConnectionParam.NewLine.CR;
            _terminalSettings.TerminalType = Poderosa.ConnectionParam.TerminalType.XTerm;
            _terminalSettings.LogSettings.Reset(logSettings);
            _terminalSettings.EndUpdate();
            IProtocolService protocolservice = TerminalSessionsPlugin.Instance.ProtocolService;

            mreConnect.Reset();
            IInterruptable interruptable = protocolservice.AsyncSSHConnect(this, ssh);

            Task.Factory.StartNew(() => AwaitConnectResult());

            return(true);
        }
Example #24
0
        //-------------------------------------------------------------------------
        // This is the one and only entry point called when Postgres loads the language handler DLL
        // At this point there is no way to report problems, so avoid any exceptions. Just store things for later use.
        public static int Entry(string arg)
        {
            // Leave these here commented out if ever needed
            //Debugger.Launch();
            //pg_elog(ElogLevel.NOTICE, $"Entry: '{arg}'");
            _initial_arg = arg;

            // These are the (static) callback functions. Look up an instance and call it...
            ConnectCallback    cncb = (h, o) => GetInstance(h).Connect(o);
            TypeCheckCallback  tccb = (h, f, n, a, r) => GetInstance(h).TypeCheck(f, a, r);
            InvokeCallback     ivcb = (h, f, n, a, r) => GetInstance(h).Invoke(f, a, r);
            GetMessageCallback gmcb = (h) => GetInstance(h).GetMessage();

            // call back with the real entry points for later use
            return(plandl_init_callback(cncb, tccb, ivcb, gmcb));
        }
        public static IAsyncResult BeginConnect(IPEndPoint dbg_ep, IPEndPoint con_ep, AsyncCallback callback)
        {
            Socket dbg_sock = null;
            Socket con_sock = null;

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

            if (con_ep != null)
            {
                con_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }

            ConnectCallback c = new ConnectCallback(ConnectInternal);

            return(c.BeginInvoke(dbg_sock, con_sock, dbg_ep, con_ep, callback, con_sock ?? dbg_sock));
        }
        public void connectTo(string ip, int port, ConnectCallback callback, object userData)
        {
            if (valid())
            {
                throw new InvalidOperationException("Have already connected!");
            }

            if (!(new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip))
            {
                IPHostEntry ipHost = Dns.GetHostEntry(ip);
                ip = ipHost.AddressList[0].ToString();
            }

            // Security.PrefetchSocketPolicy(ip, 843);
            IPAddress[]   hostAddresses = Dns.GetHostAddresses(ip);
            IPAddress[]   outIPs        = hostAddresses;
            AddressFamily addressFamily = AddressFamily.InterNetwork;

            if (Socket.OSSupportsIPv6 && this.IsHaveIpV6Address(hostAddresses, ref outIPs))
            {
                addressFamily = AddressFamily.InterNetworkV6;
            }
            _socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, NetworkInterface.TCP_PACKET_MAX * 2);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.SendBuffer, NetworkInterface.TCP_PACKET_MAX * 2);
            _socket.NoDelay = true;
            //_socket.Blocking = false;

            ConnectState state = new ConnectState();

            state.connectIP        = ip;
            state.connectPort      = port;
            state.connectCB        = callback;
            state.userData         = userData;
            state.socket           = _socket;
            state.networkInterface = this;

            Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ...");
            connected = false;

            // 先注册一个事件回调,该事件在当前线程触发
            Event.registerIn("_onConnectionState", this, "_onConnectionState");

            var v = new AsyncConnectMethod(this._asyncConnect);

            v.BeginInvoke(state, new AsyncCallback(this._asyncConnectCB), state);
        }
        public static VirtualMachine EndConnect(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            if (!asyncResult.IsCompleted)
            {
                asyncResult.AsyncWaitHandle.WaitOne();
            }

            AsyncResult     async = (AsyncResult)asyncResult;
            ConnectCallback cb    = (ConnectCallback)async.AsyncDelegate;

            return(cb.EndInvoke(asyncResult));
        }
        public void connectTo(string ip, int port, ConnectCallback callback, object userData)
        {
            if (valid())
                throw new InvalidOperationException( "Have already connected!" );

            if(!(new Regex( @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip))
            {
                IPHostEntry ipHost = Dns.GetHostEntry (ip);
                ip = ipHost.AddressList[0].ToString();
            }

            // Security.PrefetchSocketPolicy(ip, 843);
            IPAddress[] hostAddresses = Dns.GetHostAddresses(ip);
            IPAddress[] outIPs = hostAddresses;
            AddressFamily addressFamily = AddressFamily.InterNetwork;
            if (Socket.OSSupportsIPv6 && this.IsHaveIpV6Address(hostAddresses, ref outIPs))
            {
                addressFamily = AddressFamily.InterNetworkV6;
            }
            _socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, NetworkInterface.RECV_BUFFER_MAX * 2);

            ConnectState state = new ConnectState();
            state.connectIP = ip;
            state.connectPort = port;
            state.connectCB = callback;
            state.userData = userData;
            state.socket = _socket;
            state.networkInterface = this;

            Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ...");

            // 先注册一个事件回调,该事件在当前线程触发
            Event.registerIn("_onConnectStatus", this, "_onConnectStatus");

            try
            {
                _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(connectCB), state);
            }
            catch (Exception e)
            {
                state.error = e.ToString();
                Event.fireIn("_onConnectStatus", new object[]{state});
            }
        }
Example #29
0
    public void Connect(string url, ConnectCallback callback, OnMessageCallback msgHandler)
    {
        if (this._ws != null)
        {
            this._callback = null;
            this._ws.Close();
        }
        this._callback    = callback;
        this._msgCallback = msgHandler;

        _ws            = new WebSocket(url);
        _ws.OnOpen    += OnOpen;
        _ws.OnMessage += OnMessage;
        _ws.OnError   += OnError;
        _ws.OnClose   += OnClose;

        _ws.ConnectAsync();
    }
Example #30
0
        public void connectTo(string ip, int port, ConnectCallback callback, object userData)
        {
            if (valid())
            {
                throw new InvalidOperationException("Have already connected!");
            }

            if (!(new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip))
            {
                IPHostEntry ipHost = Dns.GetHostEntry(ip);
                ip = ipHost.AddressList[0].ToString();
            }

            // Security.PrefetchSocketPolicy(ip, 843);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, KBEngineApp.app.getInitArgs().getRecvBufferSize() * 2);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.SendBuffer, KBEngineApp.app.getInitArgs().getSendBufferSize() * 2);
            _socket.NoDelay = true;

            ConnectState state = new ConnectState();

            state.connectIP        = ip;
            state.connectPort      = port;
            state.connectCB        = callback;
            state.userData         = userData;
            state.socket           = _socket;
            state.networkInterface = this;

            Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ...");

            // 先注册一个事件回调,该事件在当前线程触发
            Event.registerIn("_onConnectStatus", this, "_onConnectStatus");

            try
            {
                _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(connectCB), state);
            }
            catch (Exception e)
            {
                state.error = e.ToString();
                Event.fireIn("_onConnectStatus", new object[] { state });
            }
        }
Example #31
0
    public void Connect(ConnectCallback connectCallback, ConnectCallback connectFailedCallback)
    {
        connectDelegate       = connectCallback;
        connectFailedDelegate = connectFailedCallback;

        //采用TCP方式连接
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //服务器IP地址
        IPAddress address = IPAddress.Parse(NetProtocols.SERVER_ADDRESS);

        //服务器端口
        IPEndPoint endpoint = new IPEndPoint(address, NetProtocols.SERVER_PORT);

        //异步连接,连接成功调用connectCallback方法
        IAsyncResult result = socket.BeginConnect(endpoint, new AsyncCallback(ConnectedCallback), socket);

        //这里做一个超时的监测,当连接超过5秒还没成功表示超时
        bool success = result.AsyncWaitHandle.WaitOne(5000, true);

        if (!success)
        {
            //超时
            Closed();
            NetTools.Log("connect Time Out");
            if (connectFailedDelegate != null)
            {
                connectFailedDelegate();
            }
        }
        else
        {
            //与socket建立连接成功,开启线程接受服务端数据。
            isStopReceive = false;
            Thread thread = new Thread(new ThreadStart(ReceiveSorket));
            thread.IsBackground = true;
            thread.Start();
        }

        //
        RegisterResp.RegisterAll();
    }
Example #32
0
 /// <summary>
 /// Adds a new socket to this thread. Throws an exception if we already have too many sockets.
 /// </summary>
 /// <param name="address">Address to connect to.</param>
 /// <param name="port">Port to connect to.</param>
 /// <param name="cb">A function to be called when the connection succeeds or fails.</param>
 public void AddSocket(string address, int port, ConnectCallback cb)
 {
     if (sockets == null) throw new ObjectDisposedException("NetworkThread");
     lock(this)
     {
         if (AvailableSlot() < 1) throw new Exception("Out of socket slots in this thread.");
         connectionqueue.Enqueue(new ConnQueueItem(address, port, cb));
         // If the thread is not running, start it.
         if (thread == null || (thread.ThreadState & ThreadState.Unstarted) != 0)
         {
             thread = new Thread(new ThreadStart(SocketThread));
             thread.IsBackground = true;
             thread.Start();
         }
             // Otherwise, if the thread is sleeping, wake it up.
         else if ((thread.ThreadState & ThreadState.WaitSleepJoin) != 0)
         {
             thread.Interrupt();
         }
     }
 }
Example #33
0
        private void OnConnectReply(NLRep_Connect msg, PBChannel channel, int src, uint session)
        {
            ConnectCallback cb = connect_callback_;

            if (null != cb)
            {
                bool   connectRet = false;
                string errorStr   = "Unknown Error";
                if (msg.Result == true)
                {
                    connectRet = true;
                    errorStr   = "Connect Success";
                }
                else
                {
                    connectRet = false;
                    errorStr   = msg.Error;
                }
                cb(connectRet, errorStr);
            }
        }
Example #34
0
    public void Connect(string serverIp, int serverPort, ConnectCallback connectCallback, ConnectCallback connectFailedCallback)
    {
        connectDelegate       = connectCallback;
        connectFailedDelegate = connectFailedCallback;

        //采用TCP方式连接
        ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //服务器IP地址
        IPAddress address = IPAddress.Parse(serverIp);

        //服务器端口
        IPEndPoint endpoint = new IPEndPoint(address, serverPort);

        //异步连接,连接成功调用connectCallback方法
        IAsyncResult result = ServerSocket.BeginConnect(endpoint, new AsyncCallback(ConnectedCallback), ServerSocket);

        Thread getResult = new Thread(ConnectResult);

        getResult.IsBackground = true;
        getResult.Start(result);
    }
Example #35
0
        public void ConnectServer(IPAddress ip, int port, ConnectCallback connect = null, ReceiveCallback receive = null, SendBefore send = null, ErrorCallback error = null)
        {
            if (_socket != null)
            {
                if (_socket.Connected == true)
                {
                    return;
                }
            }
            _ip              = ip;
            _port            = port;
            _connectcallback = connect;
            _receivecallback = receive;
            _sendBefore      = send;
            _errorCallback   = error;


            var listenThread = new Thread(Connect);

            listenThread.IsBackground = true;
            listenThread.Start();
        }
 /// <summary>
 /// Connect to Echelon asynchronously.
 /// </summary>
 /// <param name="callback"></param>
 public static void ConnectToEchelonAsync(ConnectCallback callback)
 {
     if (callback == null || Echelon != null)
     {
         ConnectToEchelon();
     }
     else
     {
         Thread thread = new Thread(() =>
         {
             try
             {
                 ConnectToEchelon();
                 callback(true);
             }
             catch (Exception)
             {
                 callback(false);
             }
         });
         thread.Start();
     }
 }
Example #37
0
 /// <summary>
 /// Creates a new NetworkThread instance and starts a socket connecting to the given address and port.
 /// </summary>
 /// <param name="address">The address to which the initial socket will connect. This must be either a valid DNS hostname or a valid IP address.</param>
 /// <param name="port">The remote port to which the socket will connect.</param>
 /// <param name="cb">A function to be called when the connection succeeds or fails.</param>
 public NetworkThread(string address, int port, ConnectCallback cb)
     : this()
 {
     AddSocket(address, port, cb);
 }
Example #38
0
 public ConnQueueItem(string address, int port, ConnectCallback cb)
 {
     this.address = address;
     this.port = port;
     this.cb = cb;
 }