/// <summary> /// The AsyncResult callback for the BegingReceive function. It receives a message, splits it by ";" and send each line to the <see cref="UdpGenericTranslator"/>. It also transforms the message to all lower case. /// </summary> /// <param name="res">the async result of the begin receive function</param> private void AsyncRcvData(IAsyncResult res) { if (_isConnected == false || _client == null) { return; } byte[] data; try { data = _client.EndReceive(res, ref _anyIp); } catch (Exception e) { Debug.LogError(e + e.StackTrace); _client.BeginReceive(AsyncRcvData, _client); return; } _client.BeginReceive(AsyncRcvData, _client); var message = Encoding.UTF8.GetString(data); if (message == string.Empty) { return; } //GlobalVariables.ShortTermExcitement = message; //Debug.Log(message); string[] messageList = message.Split(','); string[] result = messageList[4].Split(';'); //Debug.Log(float.Parse(result[0])); GlobalVariables.ShortTermExcitement = float.Parse(result[0]); try { message = message.ToLower(); var split = message.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in split) { if (line.Length > 1) { UdpGenericTranslator.TranslateData(line); } } } catch (Exception e) { Debug.Log(message); Debug.LogError(e.Message); Debug.LogError(e.StackTrace); } }
/// <summary> /// The AsyncResult callback for the BegingReceive function. It receives a message, splits it by ";" and send each line to the <see cref="UdpGenericTranslator"/>. It also transforms the message to all lower case. /// </summary> /// <param name="res">the async result of the begin receive function</param> private void AsyncRcvData(IAsyncResult res) { if (_isConnected == false) { return; } byte[] data; try { data = _client.EndReceive(res, ref _anyIp); } catch (Exception e) { Debug.LogError(e.Message); _client.BeginReceive(AsyncRcvData, _client); return; } _client.BeginReceive(AsyncRcvData, _client); var message = Encoding.UTF8.GetString(data); if (message == string.Empty) { return; } try { message = message.ToLower(); var split = message.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in split) { if (line.Length > 1) { UdpGenericTranslator.TranslateData(line); } } } catch (Exception e) { Debug.Log(message); Debug.LogError(e.Message); Debug.LogError(e.StackTrace); } }
/// <summary> /// Initiate the listening process. This processes used the Microsoft UdpClient class and works asynchronously (multi-threaded). it also initializes the <see cref="UdpGenericTranslator"/> /// </summary> public void Init() { if (_isConnected) { return; } _isConnected = true; UdpGenericTranslator.InitializeTranslator(); _anyIp.Port = Port; _client = new UdpClient(Port) { Client = { ReceiveBufferSize = 8192 } }; _client.BeginReceive(AsyncRcvData, _client); }