//------------------------------------------------------------------------- void _onSocketConnected(object client, EventArgs args) { if (OnSocketConnected != null) { OnSocketConnected.Invoke(this, args); } }
public void Connect() { socket = new WebSocket($"wss://{server}/socket.io/?EIO=3&transport=websocket") { Log = { Level = LogLevel.Trace, File = @"C:\Users\solca\RiderProjects\prco204-supine\wslog.txt" } }; socket.OnClose += (sender, args) => { OnSocketDisconnected?.Invoke(String.Format("[{0}] {1}", args.Code, args.Reason)); StopNetworkTick(); }; socket.OnMessage += (sender, e) => DecodeMessage(e.Data); socket.OnOpen += (sender, e) => { Debug.Log("Server connection established"); InvokeRepeating("SendHeartbeat", 25, 25); // Heartbeat every 25s after 25s OnSocketConnected?.Invoke(); //StartNetworkTick(); }; socket.OnError += (sender, e) => { OnSocketError?.Invoke(e.Message + " - " + e.Exception.StackTrace); StopNetworkTick(); throw e.Exception; }; socket.Connect(); }
//--------------------------------------------------------------------- public void Update(float elapsed_tm) { if (mSession != null) { mSession.Update(); } while (true) { SocketEvent socket_event; socket_event.type = eSocketEventType.Null; socket_event.client = null; socket_event.args = null; lock (LockWorker) { if (mSocketEvent.Count > 0) { socket_event = mSocketEvent.Dequeue(); } } if (socket_event.type == eSocketEventType.Null) { break; } switch (socket_event.type) { case eSocketEventType.Connected: { if (OnSocketConnected != null) { OnSocketConnected.Invoke(null, socket_event.args); } } break; case eSocketEventType.Closed: { if (OnSocketClosed != null) { OnSocketClosed.Invoke(null, socket_event.args); } } break; case eSocketEventType.Error: { if (OnSocketError != null) { OnSocketError.Invoke(null, (SocketErrorEventArgs)socket_event.args); } } break; } } }
public async Task OpenAsync() { var host = uri.Host; var port = uri.Port; try { Console.Write($"WebSocketClient: Connecting to {uri}..."); var ipHostInfo = Dns.GetHostEntry(host); var ipAddress = ipHostInfo.AddressList.Where((i) => i.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault(); var localEndPoint = new IPEndPoint(ipAddress, port); socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); await socket.ConnectAsync(localEndPoint); OnSocketConnected.Invoke(this, null); Console.WriteLine($"Connected!"); stream = GetNetworkStream(); var doNotWait = StartHandshakeWithServer(); } catch (Exception exception) { OnError.Invoke(this, exception); } }
private void _ws_OnOpen(object sender, EventArgs e) { OnSocketConnected?.Invoke(this, e); }
public BluetoothDeviceConnection(TaskScheduler UITaskScheduler) : base(UITaskScheduler) { DeviceSelector = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); _ConsoleBuffer = new StringBuilder(64); OnDeviceConnected += new TypedEventHandler <DeviceConnection, DeviceInformation>(async(connection, deviceInfo) => { if (IsDeviceConnected) { // Create a standard networking socket and connect to the target _socket = new StreamSocket(); _connectAction = _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); try { await _connectAction.AsTask().ContinueWith(async(task) => { if (task.Status != TaskStatus.RanToCompletion) { CloseDevice(); return; } _writer = new DataWriter(_socket.OutputStream); _writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; _reader = new DataReader(_socket.InputStream); _reader.InputStreamOptions = InputStreamOptions.Partial; _reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; // String builder storing the last received JSON string. StringBuilder _JSONRawData = new StringBuilder(); _isSocketConnected = true; OnSocketConnected?.Invoke(this, deviceInfo); // Receiving loop while (_reader != null) { uint size; if (_isJSONCommunicationStarted) { size = await _reader.LoadAsync(512); } else { size = await _reader.LoadAsync(sizeof(byte)); } if (size < sizeof(byte)) { // The underlying socket was closed before we were able to read the whole data CloseDevice(); break; } while (_reader.UnconsumedBufferLength > 0) { var c = (char)_reader.ReadByte(); if (_isJSONCommunicationStarted) { if (c == '\n') { try { var DeserializedData = JsonConvert.DeserializeObject <JSONDataSource>(_JSONRawData.ToString(), new JsonDataSourceConverter(), new BoolConverter()); if (DeserializedData != null) { OnJSONObjectReceived?.Invoke(this, DeserializedData); } } catch (Newtonsoft.Json.JsonReaderException) { } finally { _JSONRawData.Clear(); } } else { _JSONRawData.Append(c); } } else { // TODO: correct bug: "start" don't append in _ConsoleBuffer (add a boolean 'FirstJSONObjReceived' ?) // If the received data isn't JSON objects, add it to _ConsoleBuffer _ConsoleBuffer.Append(c); } } // Notify buffer changed if (!_isJSONCommunicationStarted) { ConsoleBufferChanged?.Invoke(this, null); } } }, UITaskScheduler); } catch (TaskCanceledException) { CloseDevice(); } } }); OnDeviceClose += new TypedEventHandler <DeviceConnection, DeviceInformation>((connection, deviceInfo) => { if (_connectAction?.Status == AsyncStatus.Started) { _connectAction?.Cancel(); } _connectAction = null; _reader?.Dispose(); _reader = null; _writer?.Dispose(); _writer = null; _isSocketConnected = false; _socket?.Dispose(); _socket = null; OnSocketClose?.Invoke(this, deviceInfo); _isJSONCommunicationStarted = false; _connectAction = null; }); }