public void Connect() { ExchangeBalances = new Dictionary <string, double>(); Bids = new SortedDictionary <double, BookEntry>(); Asks = new SortedDictionary <double, BookEntry>(); TickerData = new Dictionary <Ticker, TickerData>(); TickerAge = new Dictionary <Ticker, DateTime>(); channel_ids = new Dictionary <int, string>(); Uri endpoint_uri = new Uri(Endpoint); bool tls = endpoint_uri.Scheme == "wss"; TcpClient tcp = new TcpClient(endpoint_uri.Host, tls ? 443 : 80); client = new ClientConnection(tcp, tls, endpoint_uri.Host); Log.Info("Connecting to {0}:{1}...", endpoint_uri.Host, ((IPEndPoint)tcp.Client.RemoteEndPoint).Port); client.OnDataReceived += (sender, msg, payload) => { LastMessage = DateTime.Now; string payload_str = Encoding.UTF8.GetString(payload); try { var obj = JToken.Parse(payload_str); if (obj.Type == JTokenType.Array) // channel data { var arr = (JArray)obj; HandleChannelMessage(arr); //Log.Debug("New message from channel {0}/{1}", arr[0].Value<int>(), arr[1].Value<string>()); } else if (obj.Type == JTokenType.Object) // other data { HandleInfoMessage((JObject)obj); } else { Log.Warn("Unrecognized JToken type {0}", obj.Type); } } catch (Exception ex) { Log.Warn(ex); } }; client.PerformHandshake(endpoint_uri.Host, endpoint_uri.PathAndQuery, ""); client.StartThreads(); LastMessage = DateTime.Now; Log.Info("Connected"); OnConnect?.Invoke(this); }
public void handleConnect(IChannel channel) { OneThreadSynchronizationContext.Instance.Post((obj) => { OnConnect?.Invoke((IChannel)obj); }, channel); }
public void StartListening(String host, int port, OnReceive on_receive, OnConnect on_connect, OnDisconnect on_disconnect, OnListenError on_listen_error) { on_receive_ = on_receive; on_connect_ = on_connect; on_disconnect_ = on_disconnect; on_listen_error_ = on_listen_error; size_receiving_ = 0; IPAddress ipAddress = IPAddress.Parse(GetIPAddress(host)); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. listener_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener_.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // Bind the socket to the local endpoint and listen for incoming connections. try { listener_.Bind(localEndPoint); listener_.Listen(0); // Start an asynchronous socket to listen for connections. listener_.BeginAccept(new AsyncCallback(AcceptCallback), listener_); } catch (Exception e) { on_listen_error_(e.ToString()); } }
public async Task ReceiveAsync(int bufferSize = 1024 * 4) { OnConnect?.Invoke(this, ws.State == WebSocketState.Open); var buffer = new byte[bufferSize]; try { while (true) { var array = new ArraySegment <byte>(buffer); var result = await ws.ReceiveAsync(array, CancellationToken.None); // FIXME result.CloseStatus or !result.CloseStatus // if (result.MessageType == WebSocketMessageType.Close || !result.CloseStatus.HasValue) if (result.MessageType == WebSocketMessageType.Close || result.CloseStatus.HasValue) { break; } var data = array.Slice(0, result.Count).ToArray(); OnMessageReceive?.Invoke(this, new Message { Client = this, MessageType = result.MessageType, Data = data }); } } catch (Exception e) { Console.WriteLine(e); } Close(); }
// http://msdn.microsoft.com/en-us/library/system.net.sockets.addressfamily.aspx /// <summary> /// Connects to a vehicle on a supplied ip and port /// Clears callback functions /// Zeros out callback counter /// Registers a callback for the login /// This starts a thread for received data. /// </summary> /// <param name="vehicleIpEndPoint">Socket for vehicle</param> /// <param name="login">Login information</param> public void Connect(Broadcast bcast, Login login) { if (Socket != null) { throw new ConnectionException("Device already controlled/connected to a client."); } Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { Socket.Connect(bcast.Endpoint); } catch (SocketException ex) { throw new ConnectionException("Could not connect to vehicle.", ex); } if (!Socket.Connected) { Socket = null; throw new ConnectionException("Could not connect to vehicle."); } _callbacks.Clear(); OnConnect?.Invoke(bcast); _thread.Start(); Login(login); }
public bool InitDeviceAuto() { _log.TraceInfo("Beginning AUTO initialization..."); string order = ""; foreach (int item in _xattr) { order += "," + item.ToString(); } order = order.TrimStart(','); _log.TraceInfo("Auto Protocol Order: " + order); _log.TraceInfo("Application Layer Protocol: " + STDType.ToString()); SetDevice(HardwareType.ELM327); bool flag; DllSettings.StandardIndex = STDType; flag = _obdDevice.InitializeAuto(DllSettings); STDType = _obdDevice.GetStandardType(); if (flag) { DllSettings.ProtocolIndex = _obdDevice.GetProtocolType(); DllSettings.ComPort = _obdDevice.GetComPortIndex(); SaveDllSettings(DllSettings); OnConnect?.Invoke(); return(true); } return(false); }
/// <summary> /// 处理客户端连接请求 /// </summary> /// <param name="result"></param> private void Accept(IAsyncResult socket) { // 还原传入的原始套接字 Socket SockeServer = (Socket)socket.AsyncState; // 在原始套接字上调用EndAccept方法,返回新的套接字 Socket SockeClient = SockeServer.EndAccept(socket); byte[] buffer = new byte[4096]; try { //接收客户端的数据 SockeClient.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(HandShake), SockeClient); //保存登录的客户端 Session session = new Session(buffer, SockeClient); lock (SessionPool) { if (SessionPool.ContainsKey(session.IP)) { this.SessionPool.Remove(session.IP); } this.SessionPool.Add(session.IP, session); } //准备接受下一个客户端 SockeServer.BeginAccept(new AsyncCallback(Accept), SockeServer); OnConnect?.Invoke(this, new ClientConnectEventArgs(session)); Console.WriteLine(string.Format("WebSocketServer:Client {0} connected", SockeClient.RemoteEndPoint)); } catch (Exception ex) { Console.WriteLine("Error : " + ex.ToString()); } }
private void ConnectCandidate() { if (_nearJointPoint == null || _senderJointPoint == null) { return; } if (_nearJointPoint.JointBehaviour._rigidbody.isKinematic != _senderJointPoint.JointBehaviour._rigidbody.isKinematic) { Debug.Log($"Can not connect joints with different kinematics"); return; } Debug.Log($"Joint invoke! {_senderJointPoint}"); TransformToJoint(_nearJointPoint.JointBehaviour.gameObject, _nearJointPoint, _senderJointPoint); _senderJointPoint.Connect(_nearJointPoint.JointBehaviour.gameObject, _nearJointPoint); if (AutoLock) { _senderJointPoint.Lock(); } OnConnect?.Invoke(); _nearJointPoint.JointBehaviour.OnConnect?.Invoke(); }
private void ConnectInternal() { try { //start keepAlive timer only on first connect if (_reconnectTimer == null) { _reconnectTimer = new System.Timers.Timer(_settings.ReconnectInterval * 1000); _reconnectTimer.Elapsed += ReconnectTimer_Elapsed;; _reconnectTimer.Start(); } if (_isInConnectInternal) { return; } _isInConnectInternal = true; if (_socket != null) { try { _socket.Dispose(); } catch { } _socket = null; } foreach (var serverAddress in _settings.ServerAddressList) { try { _socket = TcpSocketsUtils.Connect(serverAddress.Item1, serverAddress.Item2); break; } catch { OnDebugLog?.Invoke(DebugLogType.ConnectFailed, $" host:{serverAddress.Item1} port:{serverAddress.Item2} "); } } _connectEvent.Set(); if (_socket != null) { IsConnected = true; OnConnect?.Invoke(); TcpSocketsUtils.Recv( _socket, OnRecv, OnExcp, OnRecvProgress, _settings.ReceiveBufferSize == 0 ? TcpSocketsUtils.ms_DefualtReceiveBufferSize : _settings.ReceiveBufferSize, true); } } catch (Exception ex) { } finally { _isInConnectInternal = false; } }
private async void NewClient(Socket socket, int millisecondsDelay) { try { socket.Connect(address); OnConnect?.Invoke(this, new EventArgs()); } catch (Exception exception) { OnConnectException?.Invoke(this, new ExceptionEventArgs(socket, exception)); } while (true) { try { socket.Send(messageBuffer); OnSend?.Invoke(this, new EventArgs()); } catch (Exception exception) { OnSendException?.Invoke(this, new ExceptionEventArgs(socket, exception)); } await Task.Delay(millisecondsDelay); } }
public async void Connect() { Logger.Debug("Signaling", "Connect"); if (closed) { Logger.Debug("Signaling", "already closed"); return; } try { await socket.ConnectAsync(new Uri($"{endpoint}?channel_id={channelId}")); socketWriter = new DataWriter(socket.OutputStream); OnConnect?.Invoke(); await SendConnectMessage(); } catch (Exception ex) { Logger.Debug("Signaling", $"failed to connect websocket: {ex.Message}"); OnError?.Invoke(ErrorType.SocketCantConnect); } }
/// <summary> /// Handles connection info response from PlayFab (called on Connect) and starts the connection to the hub. /// </summary> /// <param name="connectionInfo"></param> private async void OnConnectionInfoSuccess(GetConnectionInfoResponse connectionInfo) { _accessToken = connectionInfo.AccessToken; _uri = connectionInfo.Url; CreateHubConnection(); try { if (Debugging) { Debug.Log("Trying to connect to hub"); } await _hubConnection.StartAsync(); if (Debugging) { Debug.Log("Connected To Hub"); } OnConnect?.Invoke(); } catch (Exception ex) { OnConnectionError?.Invoke(new PlayFabError() { Error = PlayFabErrorCode.InternalServerError, ErrorMessage = string.Format("PersistentSocket failed to start the connection with the message: {0}", !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty) }); } }
private void onConnStateChange(object sender, StateChangeEventArgs e) { if (e.CurrentState == ConnectionState.Open) { _connected = true; backlogTimer.Start(); OnConnect?.Invoke(this, EventArgs.Empty); sendNext(); } else if (e.CurrentState == ConnectionState.Closed || e.CurrentState == ConnectionState.Broken) { backlogTimer.Stop(); string oldDbString = dbString; dbString = null; conn = null; command = null; backlog.Clear(); _connected = false; _busy = false; OnDisconnect?.Invoke(this, EventArgs.Empty); } }
public async Task Connect() { if (Client == null) { throw new NotActiveException(); } if (Client.IsConnecting || Client.IsConnected) { return; } try { Client.Connect(); await Task.Run(() => { // Await connectiong while (Client.IsConnecting || MainActivity.Activity.AuthInProgress) { Task.Delay(50); } }); if (Client.IsConnected) { OnConnect?.Invoke(); } } catch (Exception e) { OnError?.Invoke(e.Message); } }
public void Service(uint timeout) { while (Service(out ENetEvent e, timeout)) { if (e is ENetNoneEventArgs) { continue; } if (e is ENetConnectEventArgs connect) { OnConnect?.Invoke(this, connect); continue; } if (e is ENetDisconnectEventArgs disconnect) { disconnect.Peer.RaiseDisconnectEvent(disconnect.Data); continue; } if (e is ENetReceiveEventArgs receive) { receive.Peer.RaiseReceiveEvent(receive.Packet); continue; } } }
public void Connect() { ConnectionFailed = false; Task.Run(() => { try { if (Ip == null) { return; } OnConnecting?.Invoke(this, null); client?.Dispose(); client = new TcpClient(Ip.ToString(), Port) { NoDelay = true }; nwStream = client.GetStream(); if (TurnOnWhenConnected) { Turn(true); } OnConnect?.Invoke(this, null); } catch (Exception) { ConnectionFailed = true; OnConnectFail?.Invoke(this, null); } }); }
private void AsyncInit(TcpListener tcpListener, string hostName, int port) { while (!disposed) { var accept = tcpListener.AcceptTcpClientAsync(); if (accept.Wait(1000, tokenSource.Token) && !tokenSource.IsCancellationRequested) { var localClient = accept.GetAwaiter().GetResult(); OnConnect?.Invoke(this, new ProxyConnectionEventArgs(localClient)); var remoteClient = new TcpClient() { NoDelay = true }; tokenSource.Token.Register(() => { localClient.Dispose(); remoteClient.Dispose(); }); remoteClient.ConnectAsync(hostName, port).Wait(tokenSource.Token); if (!tokenSource.IsCancellationRequested) { Task.Factory.StartNew(() => { ForwardToSql(localClient, remoteClient); }); Task.Factory.StartNew(() => { ForwardToClient(localClient, remoteClient); }); } else { Trace.TraceInformation("AsyncInit aborted due to cancellation token set"); } } } }
public Host(int port) { EnableHandshake = true; AllowedTokens = AllowedTokens.Any; //ValidateMessageTypes(); _listenThread = new Thread(() => Listen(port)); _port = port; _isListening = false; _connectionManager = new ConnectionManager(); _receiveHandlers = new Dictionary <short, IList <ReceiveHandler> >(); Rnd = new Random(); AddHandler((short)MessageType.Token, (m, c) => { _hostToken = m.ConnectionToken; if (OnConnect != null) { OnConnect.Invoke(); } }); AddHandler((short)MessageType.Handshake, (m, c) => { if (!EnableHandshake) { return; } if (ConnectionCreated != null) { ConnectionCreated.Invoke(c); } SendToken(c); }); AddHandler((short)MessageType.Ack, (m, c) => { c.ProcessAck(m); }); ServerTimer.OnTick += ServerTick; }
private async Task HandleWebSocketAsync(WebSocket websocket) { try { OnConnect?.Invoke(websocket); while (websocket.IsConnected) { var message = await websocket.ReadStringAsync(CancellationToken.None) .ConfigureAwait(false); if (message != null) { OnMessage?.Invoke(websocket, message); } } OnDisconnect?.Invoke(websocket); } catch (Exception ex) { OnError?.Invoke(websocket, ex); } finally { websocket.Dispose(); } }
public new bool Connect(string ip, int port) { if (IsConnected) { return(true); } mServerAdress = new IPEndPoint(IPAddress.Parse(ip), port); Connect(mServerAdress); if (IsConnected == false) { Close(); return(false); } mReceiveThread = new Thread(ReceiveThread); mSendThread = new Thread(SendThread); mReceiveThread.Start(); mSendThread.Start(); OnConnect?.Invoke(); return(true); }
public bool BeginConnect(IPEndPoint ep, Token token) { _hostToken = token; _connectionManager.Add(token, new Connection(ep)); OnConnect.Invoke(); return(true); }
public CommServer() { server = new TcpPackServer(); queue = new BlockingCollection <IMsg>(); server.OnAccept += delegate(IServer sender, IntPtr connId, IntPtr client) { OnConnect?.Invoke(); return(HandleResult.Ok); }; server.OnReceive += delegate(IServer sender, IntPtr connId, byte[] bytes) { Message message = new Message(); message.MergeFrom(bytes); try { queue.Add(message);//理论上这里可能抛出异常ObjectDisposedException或InvalidOperationException } catch (Exception e) { Console.WriteLine("Exception occured when adding an item to the queue:" + e.Message); } OnReceive?.Invoke(); return(HandleResult.Ok); }; }
public void Start() { // Only start once if (Started) { return; } Started = true; Client.Connect(IPAddress.Loopback, Constants.ClientConnectionPort); OnConnect?.Invoke(this, new IDEventArgs(ID)); byte[] IDData = Encoding.UTF8.GetBytes(ID.ToString() + Environment.NewLine); Client.GetStream().Write(IDData, 0, IDData.Length); Worker = new Thread(new ThreadStart(async() => { using (StreamReader Reader = new StreamReader(Client.GetStream(), Encoding.UTF8)) { do { if (ShouldStop) { break; } else { Thread.Sleep(Constants.WorkerDelay); } string Line = await Reader.ReadLineAsync(); OnMessage?.Invoke(this, new MessageEventArgs(ID, Line)); } while (!ShouldStop); } })); Worker.Start(); }
public void StartListening(String host, int port, OnConnect on_connect, OnDisconnect on_disconnect) { on_connect_ = on_connect; on_disconnect_ = on_disconnect; size_receiving_ = 0; lock_ = new object(); queue_ = new Deque <byte>(1000000); IPAddress ipAddress = IPAddress.Parse(GetIPAddress(host)); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. listener_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen for incoming connections. try { listener_.Bind(localEndPoint); listener_.Listen(0); // Start an asynchronous socket to listen for connections. listener_.BeginAccept(new AsyncCallback(AcceptCallback), listener_); } catch (Exception e) { on_disconnect_(e.ToString()); } }
private static async void Connect() { var client = new Client(); client.Handler = HandleSignal; await client.Initialize(Config.UserId.ToString()); var retry = 0; var resetTimer = new Timer(10000); resetTimer.Elapsed += (s, e) => retry = 0; IsRunning = true; OnConnect?.Invoke(); while (!await client.Start() && retry < 3) { if (retry > 0) { resetTimer.Stop(); } retry++; resetTimer.Start(); } IsRunning = false; OnExit?.Invoke(); }
private void timeoutHandler() { // TODO: differentiate between a loss of connection and commands that just aren't responded too System.Diagnostics.Debugger.Break(); bool connected = deviceCommDriver.IsOpen(); // if the connection fails, log a message to the console and keep retrying for 1 minute if (!connected) { MainPage.ShowText("Connection failed. Retrying..."); deviceCommDriver.Close(); DateTime dtStart = DateTime.Now; DateTime dtStopAt = dtStart.AddSeconds(retrySeconds); while (DateTime.Now < dtStopAt && !connected) { System.Diagnostics.Debugger.Break(); Thread.Sleep(500); deviceCommDriver.BtConnect(deviceId).ConfigureAwait(false); } } if (connected) { OnConnect.Invoke(this); } else { System.Diagnostics.Debugger.Break(); } }
public ConnectStage(Regulus.Remoting.Ghost.TProvider<Project.SamebestKeys.IConnect> connect_provider, OnConnect connect) { // TODO: Complete member initialization this._ConnectProvider = connect_provider; _Connect = connect; _Connecter = new Connect(); }
/// <summary> /// Start listening for incoming connections /// </summary> private void StartServer() { InitializeSocket(); // Create a task that will run and search for connections Task.Run(() => { if (handler == null && IsClient == false) { try { handler = new ConnectionHandler(Socket.Accept()); handler.MessageReceived += ReceiveData; handler.OnDisconnect += ClientDisconnected; System.Diagnostics.Debug.WriteLine("Triggering client connect"); OnConnect?.Invoke(this, new SocketEventArgs(handler.Socket)); } catch { Close(); } } }); }
public static void FireOnConnect() { if (OnConnect != null) { OnConnect.Invoke(); } }
public async Task ReceiveAsync(int bufferSize = 1024 * 4) { OnConnect?.Invoke(this, ws.State == WebSocketState.Open); try { while (true) { var buffer = new byte[bufferSize]; var result = await ws.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close || !result.CloseStatus.HasValue) { break; } OnMessageReceive?.Invoke(this, new Message { Client = this, MessageType = result.MessageType, Data = buffer }); } } catch { } Close(); }
private async Task EventLoop() { var token = _eventLoopCancellation.Token; var buffer = new byte[RECEIVE_CHUNK_SIZE]; var segment = new ArraySegment <byte>(buffer); var memoryStream = new MemoryStream(); // Connect socket. await _socket.ConnectAsync(_uri, token); // Run event loop. try { await(OnConnect?.Invoke() ?? Task.CompletedTask); // Receive messages. while (WebSocketState.Open == _socket.State) { WebSocketReceiveResult received; do { received = await _socket.ReceiveAsync(segment, token); memoryStream.Write(buffer, 0, received.Count); // Don't use async, memoryStream doesn't do IO. }while (!received.EndOfMessage); // Trigger event. ToArray makes copy of buffer. await(OnMessage?.Invoke(memoryStream.ToArray()) ?? Task.CompletedTask); // Reset memoryStream (also sets the position to zero). memoryStream.SetLength(0); } } finally { // Trigger OnDisconnect. try { await(OnDisconnect?.Invoke() ?? Task.CompletedTask); } finally { // Close Socket. try { await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, token); } catch { _socket.Abort(); } finally { _socket.Dispose(); } } } }
public void Connect(byte chServerType, String m_serverIP, int m_serverPort, OnConnect dlg = null) { Guid m_Version = new Guid ("{0x5f6f921f,0x285f,0x40dc,{0x8f,0xd3,0xcf,0x5a,0xb3,0x84,0x80,0x66}}"); NetConnectionParam cp = new NetConnectionParam (); cp.protocolVersion = m_Version; cp.serverIP = m_serverIP; cp.serverPort = (ushort)m_serverPort; #if UNITY_WEBPLAYER Security.PrefetchSocketPolicy(m_serverIP, m_serverPort); #endif if(dlg != null) { ConnectHandler = dlg; } if (m_Client.Connect (cp) == false) { if (dlg != null) { dlg(false); } } }
public static extern void HP_Set_FN_Client_OnConnect(IntPtr pListener, OnConnect fn);
IEnumerator<ITask> OnConnectHandler(OnConnect onConnect) { if (onConnect.DriveControl == _driveControl) { UriBuilder builder = new UriBuilder(onConnect.Service); builder.Scheme = new Uri(ServiceInfo.Service).Scheme; ds.DirectoryPort port = ServiceForwarder<ds.DirectoryPort>(builder.Uri); // TT Nov-2006 - Changed for new CTP // ds.Get get = new ds.Get(GetRequestType.Instance); ds.Get get = new ds.Get(); port.Post(get); ServiceInfoType[] list = null; yield return Arbiter.Choice(get.ResponsePort, delegate(ds.GetResponseType response) { list = response.RecordList; }, delegate(Fault fault) { list = new ServiceInfoType[0]; LogError(fault); } ); WinFormsServicePort.FormInvoke( delegate() { _driveControl.ReplaceDirectoryList(list); } ); } }