// receive thread private void ReceiveData() { client = new UdpClient(); IPEndPoint localEp = new IPEndPoint(IPAddress.Any, port); client.Client.Bind(localEp); client.JoinMulticastGroup(IPAddress.Parse(MULTICAST_ADDR)); while (true) { try { byte[] data = client.Receive(ref localEp); string text = Encoding.UTF8.GetString(data); string[] message = text.Split(','); Vector3 result = new Vector3(float.Parse(message[0]), float.Parse(message[1]), float.Parse(message[2])); print(">> " + result); lastReceivedUDPPacket = result; } catch (Exception err) { print(err.ToString()); } } }
public static void Main() { byte[] data = new byte[1024]; string input, stringData; UdpClient server = new UdpClient("127.0.0.1", 9877); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9876); string welcome = "Hello, are you there?"; data = Encoding.ASCII.GetBytes(welcome); server.Send(data, data.Length); data = server.Receive(ref sender); Console.WriteLine("Message received from {0}:", sender.ToString()); stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine(stringData); while(true){ input = Console.ReadLine(); if (input == "exit") break; server.Send(Encoding.ASCII.GetBytes(input), input.Length); data = server.Receive(ref sender); } Console.WriteLine("Stopping client"); server.Close(); }
public static void Main() { byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9876); UdpClient newsock = new UdpClient(ipep); Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9877); data = newsock.Receive(ref sender); Console.WriteLine("Message received from {0}:", sender.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length)); string msg = Encoding.ASCII.GetString(data, 0, data.Length); data = Encoding.ASCII.GetBytes(msg); newsock.Send(data, data.Length, sender); while(true){ data = newsock.Receive(ref sender); Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length)); newsock.Send(data, data.Length, sender); } }
public static void Main() { byte[] data = new byte[1024]; string input, stringData; UdpClient udpClient = new UdpClient("127.0.0.1", 9999); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); string welcome = "Hello"; data = Encoding.ASCII.GetBytes(welcome); udpClient.Send(data, data.Length); data = udpClient.Receive(ref sender); Console.WriteLine("Message received from {0}:", sender.ToString()); stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine(stringData); while(true) { input = Console.ReadLine(); udpClient.Send(Encoding.ASCII.GetBytes(input), input.Length); data = udpClient.Receive(ref sender); stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine(stringData); } udpClient.Close(); }
public void StartListener() { bool done = false; UdpClient listener = new UdpClient(listenPort); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); try { while (!done) { Console.WriteLine("Waiting for broadcast"); byte[] bytes = listener.Receive( ref groupEP); Console.WriteLine("Received broadcast from {0} :\n {1}\n", groupEP.ToString(), Encoding.ASCII.GetString(bytes,0,bytes.Length)); } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { listener.Close(); } }
public static int Main() { bool done = false; UdpClient listener = new UdpClient(listenPort); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); string received_data; byte[] receive_byte_array; try { while (!done) { Console.WriteLine("Waiting for broadcast"); // this is the line of code that receives the broadcase message. // It calls the receive function from the object listener (class UdpClient) // It passes to listener the end point groupEP. // It puts the data from the broadcast message into the byte array // named received_byte_array. // I don't know why this uses the class UdpClient and IPEndPoint like this. // Contrast this with the talker code. It does not pass by reference. // Note that this is a synchronous or blocking call. receive_byte_array = listener.Receive(ref groupEP); Console.WriteLine("Received a broadcast from {0}", groupEP.ToString()); received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length); Console.WriteLine("data follows \n{0}\n\n", received_data); } } catch (Exception e) { Console.WriteLine(e.ToString()); } listener.Close(); return 0; }
public static void Main() { string addr = "127.0.0.1"; int port = 7980; short cmd = 1; short seq = 0; string msg = "Hello"; byte[] payload = Encoding.ASCII.GetBytes(msg); byte[] packet = Packet.Create(cmd, seq, payload); UdpClient udp = new UdpClient(); var ip = IPAddress.Parse(addr); IPEndPoint ep = new IPEndPoint(ip, port); udp.Connect(ep); // send udp.Send(packet, packet.Length); // receive bool done = false; while (!done) { if (udp.Available <= 0) { IPEndPoint ep2 = new IPEndPoint(0, 0); byte[] packet2 = udp.Receive(ref ep2); Console.WriteLine("packet size: {0}", packet2.Length); Dictionary<string, object> parsed = Packet.Parse(packet2); foreach (KeyValuePair<string, object> item in parsed) { Console.WriteLine("Received:{0} = {1}", item.Key, item.Value); } done = true; } } }
private bool CheckUsb() { try { // Если буфер приема не пустой, очищаем if (_resiver != null && _resiver?.Available > 0) { _resiver.Receive(ref _remoteIpEndPoint); } _sender.Send(_comGetStatus, _comGetStatus.Length, _endPoint); var resp = _resiver?.Receive(ref _remoteIpEndPoint); //Проверка доступности ОЕД if (resp != null && resp[0] == 10 && resp[2] == 1 && resp[8] == 1) { Dispatcher.Invoke(() => { BtnIndicUsb.Background = Brushes.GreenYellow; }); return(true); } AddToOperationsPerfomed("USB не доступен."); } catch (SocketException) { AddToOperationsPerfomed("STM не вернул статус USB соединения. TimeOut."); } Dispatcher.Invoke(() => { BtnIndicUsb.Background = Brushes.OrangeRed; BtnIndicOed.Background = Brushes.OrangeRed; }); return(false); }
private static void StartListener() { //Initiate UDP server Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); UdpClient listener = new UdpClient(ListenPort); IPEndPoint groupEp = new IPEndPoint(IPAddress.Any,ListenPort); IPEndPoint responseEp; string receivedCommand; try { while (true) { //Wait for incoming command Console.WriteLine("Waiting for command"); byte[] bytes = listener.Receive( ref groupEp); receivedCommand = Encoding.ASCII.GetString(bytes,0,bytes.Length); Console.WriteLine("Received command: " + receivedCommand + " from " + groupEp.Address); //Send matching response responseEp = new IPEndPoint(groupEp.Address, ListenPort); if (receivedCommand == "U" || receivedCommand == "u") { using (StreamReader sr = new StreamReader ("/proc/uptime")) { String line = sr.ReadToEnd(); Console.WriteLine("Sending uptime: " + line); byte[] sendbuf = Encoding.ASCII.GetBytes(line); s.SendTo(sendbuf, responseEp); } } else if(receivedCommand == "L" || receivedCommand == "l") { using (StreamReader sr = new StreamReader ("/proc/loadavg")) { String line = sr.ReadToEnd(); Console.WriteLine("Sending load average: " + line); byte[] sendbuf = Encoding.ASCII.GetBytes(line); s.SendTo(sendbuf, responseEp); } } else { Console.WriteLine("Command " + receivedCommand + " not found\n"); byte[] sendbuf = Encoding.ASCII.GetBytes("Input not recognized, please try again!"); s.SendTo(sendbuf, responseEp); } } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { listener.Close(); } }
static void Main() { //データを送信するリモートホストとポート番号 string remoteHost = "127.0.0.1"; IPAddress remoteAddress = IPAddress.Parse(remoteHost); int remotePort = 2002; UdpClient udpClient = new UdpClient(); if (null != udpClient) { //ビルドのクエリを投げる string sendMsg = "test"; byte[] buff = Encoding.UTF8.GetBytes(sendMsg); udpClient?.Send(buff, buff.Length, remoteHost, remotePort); //戻り値取得 IPEndPoint remoteEP = null; buff = udpClient?.Receive(ref remoteEP); string rcvMsg = Encoding.UTF8.GetString(buff); int rtv = int.Parse(rcvMsg); Console.WriteLine(rtv); //UdpClientを閉じる udpClient?.Close(); } Console.ReadLine(); }
private void Listen() { System.Random myRandom = new System.Random(); udpClient = new UdpClient(7272, AddressFamily.InterNetwork); var endPoint = default(IPEndPoint); byte[] bytes; while (m_shouldRun) { try { bytes = udpClient.Receive(ref endPoint); if (bytes == null || bytes.Length == 0) break; int offset = 0; lock (m_threadLock) { m_head = FromOculusToUnity(Vector3FromBytes(bytes, ref offset)); m_rHand = FromOculusToUnity(Vector3FromBytes(bytes, ref offset)); //m_rHandRotation = Vector4FromBytes(bytes, ref offset); m_lHand = FromOculusToUnity(Vector3FromBytes(bytes, ref offset)); //m_lHandRotation = Vector4FromBytes(bytes, ref offset); m_rightClosed = BoolFromBytes(bytes, ref offset); } } catch (ThreadInterruptedException) { // Empty on purpose } } }
private void ReceiveData(){ client = new UdpClient(port); //Binds udp client to random port while (true) { try { IPEndPoint IPEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref IPEndPoint); string text = Encoding.UTF8.GetString(data); if(log){ Debug.Log(text); } lock(receivedUDPPackets){ receivedUDPPackets.Add(text); } } catch (Exception err) { print(err.ToString()); } } }
static void ThreadFuncReceive() { try { while (true) { //подключение к локальному хосту UdpClient uClient = new UdpClient(LocalPort); IPEndPoint ipEnd = null; //получание дейтаграммы byte[] responce = uClient.Receive(ref ipEnd); //преобразование в строку string strResult = Encoding.Unicode.GetString(responce); Console.ForegroundColor = ConsoleColor.Green; //вывод на экран Console.WriteLine(strResult); Console.ForegroundColor = ConsoleColor.Red; uClient.Close(); } } catch (SocketException sockEx) { Console.WriteLine("Ошибка сокета: " + sockEx.Message); } catch (Exception ex) { Console.WriteLine("Ошибка : " + ex.Message); } }
private static void StartListener() { bool done = false; IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); UdpClient listener = new UdpClient(groupEP); Log.Notice("Listener", "Waiting for broadcast"); try { while (!done) { byte[] bytes = listener.Receive(ref groupEP); Log.Info("Listener", "Client " + groupEP.ToString() + " is trying to connect"); listener.Connect(groupEP); Log.Succes("Listener", "Listener connected to client " + groupEP.ToString()); done = true; //TODO - rest of district server connecting } } catch (Exception e) { FrameWork.Logger.Log.Error("Listener", e.ToString()); } finally { listener.Close(); } }
void RecieveDatagram() { UdpClient receivingUdpClient = new UdpClient ( 35143 ); IPEndPoint RemoteIpEndPoint = new IPEndPoint ( IPAddress.Any, 0 ); while ( true ) { try { Byte[] receiveBytes = receivingUdpClient.Receive ( ref RemoteIpEndPoint ); returnData = Encoding.Unicode.GetString ( receiveBytes ); if ( returnData.Substring ( 0, 17 ) == "[2CatStudios:UMP]" ) { UnityEngine.Debug.Log ( "Recieved '" + returnData.ToString () + "' This message was sent on " + RemoteIpEndPoint.Address.ToString() + " via the port " + RemoteIpEndPoint.Port.ToString ()); returnData = returnData.Substring ( 17 ); } else { UnityEngine.Debug.Log ( "Data was recieved, but it was not expected." ); } } catch ( Exception e ) { UnityEngine.Debug.Log ( e.ToString ()); returnData = e.ToString (); } } }
void procComm() { port = getPort(); string ipadr = getIpadr (); client = new UdpClient (); // send string sendstr = IFmsg.text + System.Environment.NewLine; byte[] data = ASCIIEncoding.ASCII.GetBytes (sendstr); client.Send (data, data.Length, ipadr, port); // receive client.Client.ReceiveTimeout = 2000; // msec IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, 0); lastRcvd = ""; try { data = client.Receive (ref remoteIP); if (data.Length > 0) { string text = Encoding.ASCII.GetString (data); lastRcvd = text; } } catch (Exception err) { } client.Close (); }
private void ReceiveData() { client = new UdpClient(8000); while (running) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); string text = Encoding.UTF8.GetString(data); Debug.Log("Input "+text); string[] info = text.Split(':'); inputText = text; if(info[0].Equals("speed")){ speed= info[1]; } if(info[0].Equals("turn")){ axis= info[1]; } } catch (Exception err) { running =false; print(err.ToString()); } } }
private static void WontDie () { while (true) { IPEndPoint endpoint = new IPEndPoint (IPAddress.Loopback, 1900); UdpClient s = new UdpClient (); byte [] buffer = new byte [1024]; s.Send (buffer, buffer.Length, endpoint); s.Receive (ref endpoint); } }
void DoRelay() { UdpClient client = new UdpClient (setPort); client.Client.ReceiveTimeout = 300; // msec client.Client.Blocking = false; int portToReturn = 31415; // is set dummy value at first while (ToggleComm.isOn) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); string text = Encoding.ASCII.GetString(data); if (text.Length == 0) { Thread.Sleep(20); continue; } if (text.Contains(kExportCommand)) { exportData(ref client, ref anyIP); continue; } string fromIP = anyIP.Address.ToString(); int fromPort = anyIP.Port; // send to the other if (fromIP.Equals(ipadr1)) { portToReturn = fromPort; // store the port used in the "else" clause list_comm_time.Add(System.DateTime.Now); list_comm_string.Add("tx," + text); client.Send(data, data.Length, ipadr2, setPort); DebugPrintComm("1 ", fromIP, fromPort, ipadr2, setPort); } else { // delay before relay Thread.Sleep(delay_msec); list_comm_time.Add(System.DateTime.Now); list_comm_string.Add("rx," + text); client.Send(data, data.Length, ipadr1, portToReturn); DebugPrintComm("2 ", fromIP, fromPort, ipadr1, portToReturn); } } catch (Exception err) { } // without this sleep, on android, the app will freeze at Unity splash screen Thread.Sleep(200); } client.Close (); }
void ReceiveData(){ Debug.Log ("Thread Started"); IPEndPoint inAddrAny = new IPEndPoint(IPAddress.Any, 0); client = new UdpClient (port); int byteCount = 0; byte[] newestValidMessage = new byte[messageLen]; while (true) { byte[] received = client.Receive(ref inAddrAny); Debug.Log("Got " + received.Length + " bytes"); if(received.Length>=messageLen-byteCount){ //there is enough new information to complete an update int bytesLeft = messageLen-byteCount; if(received.Length-bytesLeft>messageLen){ //entirely new message contained in latest receive int remainder = (received.Length-bytesLeft)%messageLen; for(int i = received.Length-1-remainder;i>received.Length-1-remainder-messageLen;i--){ newestValidMessage[i%messageLen] = received[i]; } UpdateHands(newestValidMessage); for(int i =received.Length-1-remainder;i<received.Length;i++){ newestValidMessage[i-received.Length+1+remainder] = received[i]; } } else{ for(int i=byteCount;i<messageLen;i++){ newestValidMessage[i] = received[i-byteCount]; } UpdateHands(newestValidMessage); for(int i=messageLen;i<received.Length;i++){ newestValidMessage[i-messageLen] = received[i]; } byteCount = (byteCount+received.Length)%messageLen; } } else{ //there is not enough information to complete an update for(int i=byteCount;i<messageLen;i++){ newestValidMessage[i] = received[i-byteCount]; } byteCount+=received.Length; } } }
public static void Main () { var ip = IPAddress.Parse ("239.255.255.250"); while (true) { UdpClient udp = new UdpClient (3802); udp.JoinMulticastGroup (ip, 1); IPEndPoint dummy = null; udp.Receive (ref dummy); Console.WriteLine ("Received"); udp.DropMulticastGroup (ip); udp.Close (); } }
private void ConnectUDP() { print("Connect UDP"); unityIPEP = new IPEndPoint(Client.IP, 64582); kinectIPEP = new IPEndPoint(IPAddress.Any, 0); socket = new UdpClient(unityIPEP); print("Waiting for Initial Message"); udpMessage = socket.Receive(ref kinectIPEP); print("Initial Message Received"); connected = true; }
public Message MessageAvailable() { Log.InfoFormat(@"Packet available"); var ep = new IPEndPoint(IPAddress.Any, 0); byte[] receiveBytes = _udpClient?.Receive(ref ep); Log.Debug($"Bytes received: {FormatBytesForDisplay(receiveBytes)}"); _readWrite.DecodeMessage(receiveBytes); Message result = _readWrite.targetMessage; result.fromAddress = ep; if (result != null) { Log.InfoFormat($"Received type: '{result.thisMessageType}' " + $" content: '{result.messageBody}' from: {result.fromAddress}"); } else { Log.Warn(@"Data received, but could not be decoded"); } return(result); }
// receive thread private void ReceiveData() { client = new UdpClient(port); while (true) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); string text = Encoding.UTF8.GetString(data); lastReceivedUDPPacket=text; allReceivedUDPPackets=allReceivedUDPPackets+text; }catch (Exception err) { } } }
private void ReceiveData() { client = new UdpClient(port); while (m_keepRunning) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); // Bytes mit der UTF8-Kodierung in das Textformat kodieren. string text = Encoding.UTF8.GetString(data); Debug.Log(text); string[] words = text.Split(' '); Quaternion q = new Quaternion(float.Parse(words[12]), float.Parse(words[13]), float.Parse(words[14]), float.Parse(words[15])); Vector3 t = new Vector3(float.Parse(words[18]), float.Parse(words[19]), float.Parse(words[20])); m_newData = new Pose(); UbiMeasurementUtils.coordsysemChange(t, ref m_newData.pos); UbiMeasurementUtils.coordsysemChange(q, ref m_newData.rot); } catch (Exception err) { Debug.Log(err.ToString()); } } client.Close(); }
protected override void Execute() { UdpClient server = null; server = new UdpClient(8080) { DontFragment = true }; IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 8080); for(;;){ byte[] receive = server.Receive(ref endPoint); retrievedPacket(receive.Length, receive); if(terminate) break; } logger.Log("Thread Stop"); }
public Message Receive(int timeout) { Log.Debug("Entering Receive"); Message result = null; try { // Wait for some data to become available while (CommunicationsEnabled && _udpClient?.Available <= 0 && timeout > 0) { Thread.Sleep(10); timeout -= 10; } // If there is data receive and communications are enabled, then read that data if (CommunicationsEnabled && _udpClient?.Available > 0) { Log.InfoFormat(@"Packet available"); var ep = new IPEndPoint(IPAddress.Any, 0); byte[] receiveBytes = _udpClient?.Receive(ref ep); Log.Debug($"Bytes received: {FormatBytesForDisplay(receiveBytes)}"); result = Message.Create(receiveBytes); if (result != null) { result.SenderEndPoint = ep; Log.InfoFormat($"Received {result} from {ep}"); } else { Log.Warn(@"Data received, but could not be decoded"); } } } catch (SocketException err) { if (err.SocketErrorCode != SocketError.TimedOut && err.SocketErrorCode != SocketError.ConnectionReset) { Log.ErrorFormat($"Socket error: {err.SocketErrorCode}, {err.Message}"); } } catch (Exception err) { Log.ErrorFormat($"Unexpected expection while receiving datagram: {err} "); } Log.Debug("Leaving Receive"); return(result); }
static void Main() { //データを送信するリモートホストとポート番号 string remoteHost = "127.0.0.1"; IPAddress remoteAddress = IPAddress.Parse(remoteHost); int remotePort = 2002; UdpClient udpClient = new UdpClient(); if (null != udpClient) { //ビルドのクエリを投げる { string sendMsg = "test"; byte[] buff = Encoding.UTF8.GetBytes(sendMsg); udpClient?.Send(buff, buff.Length, remoteHost, remotePort); } //戻り値取得 IPEndPoint remoteEP = null; udpClient.Client.ReceiveTimeout = 10000; int rtv = -1; { byte[] buff = null; try { buff = udpClient?.Receive(ref remoteEP); } catch (SocketException e) { } if (null != buff) { string rcvMsg = Encoding.UTF8.GetString(buff); int.TryParse(rcvMsg, out rtv); } } Console.WriteLine(rtv); //UdpClientを閉じる udpClient?.Close(); } Console.ReadLine(); }
private void ReceiveData() { client = new UdpClient (port); while (true) { try{ IPEndPoint anyIP = new IPEndPoint(IPAddress.Parse(address), port); byte[] data = client.Receive(ref anyIP); string text = Encoding.UTF8.GetString(data); //print (">> " + text); lastReceivedUDPPacket=text; allReceivedUDPPackets=allReceivedUDPPackets+text; string[] numberStrs = text.Split(' '); string debugNumbers = ""; for (int i = 0; i < numberStrs.Length; ++i) { debugNumbers += numberStrs[i] + ", "; } print (debugNumbers); cameraPos.x = float.Parse(numberStrs[0]); cameraPos.y = float.Parse (numberStrs[1]); cameraPos.z = float.Parse (numberStrs[2]); rotationAngles.x = float.Parse (numberStrs[3]); rotationAngles.y = float.Parse (numberStrs[4]); rotationAngles.z = float.Parse (numberStrs[5]); mouthPos.x = float.Parse (numberStrs[6]); mouthPos.y = float.Parse (numberStrs[7]); mouthPos.z = float.Parse (numberStrs[8]); mouthRatio = float.Parse (numberStrs[9]); float faceRectangleX = float.Parse (numberStrs[10]) * Screen.width; float faceRectangleY = float.Parse(numberStrs[11]) * Screen.height; float faceRectangleWidth = float.Parse (numberStrs[12]) * Screen.width; float faceRectangleHeight = float.Parse(numberStrs[13]) * Screen.height; faceRectangle = new Rect(faceRectangleX, faceRectangleY, faceRectangleWidth, faceRectangleHeight); //print (faceRectangle); }catch(Exception e){ print (e.ToString()); } } }
protected virtual void ReceiveUpdateLoop() { while (UpdateClient != null) { Thread.Sleep(0); IPEndPoint known = UpdateEndPoint ?? ManagementEndPoint; IPEndPoint remote = known; byte[] data = null; try { // Let's just hope that we always receive a full frame... // Console.WriteLine("Starting receive update"); data = UpdateClient?.Receive(ref remote); // Console.WriteLine($"Finished receive update from {remote}: {data.ToHexadecimalString()}"); } catch (Exception e) { Logger.Log(LogLevel.Warn, "ghostnet-con", "Failed receiving update frame"); LogContext(LogLevel.Warn); e.LogDetailed(); if (DisposeOnFailure) { Dispose(); return; } } if (known != null && !remote.Address.Equals(known.Address)) { Logger.Log(LogLevel.Warn, "ghostnet-con", $"Received update data from unknown remote {remote}: {data.ToHexadecimalString()}"); continue; } try { using (MemoryStream bufferStream = new MemoryStream(data)) using (BinaryReader bufferReader = new BinaryReader(bufferStream)) { GhostNetFrame frame = new GhostNetFrame(); frame.Read(bufferReader); // Logger.Log(LogLevel.Verbose, "ghostnet-con", "Received update frame"); ReceiveUpdate(remote, frame); } } catch (Exception e) { Logger.Log(LogLevel.Warn, "ghostnet-con", "Failed parsing update frame"); LogContext(LogLevel.Warn); e.LogDetailed(); Console.WriteLine("Data:"); Console.WriteLine(data.ToHexadecimalString()); // Don't dispose - maybe upcoming data isn't broken? } } }
private void ReceiveData() { client = new UdpClient(port); while (true) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Broadcast, port); byte[] data = client.Receive(ref anyIP); strReceiveUDP = Encoding.UTF8.GetString(data); // Simple Debug. Must be replaced with SendMessage for example. Debug.Log(strReceiveUDP); // } catch (Exception err) { print(err.ToString()); } } }
private void ReceiveData(){ client = new UdpClient (port); while (true) { try{ IPEndPoint anyIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); byte[] data = client.Receive(ref anyIP); string text = Encoding.UTF8.GetString(data); print (">> " + text); lastReceivedUDPPacket=text; allReceivedUDPPackets=allReceivedUDPPackets+text; xPos = float.Parse(text); xPos *= 0.021818f; }catch(Exception e){ print (e.ToString()); } } }
private void ReceiveData() { UdpClient client = new UdpClient(26000); while (true) { try { if(m_Process.HasExited) return; IPEndPoint anyIP = new IPEndPoint(IPAddress.Broadcast, 26000); byte[] data = client.Receive(ref anyIP); m_Word = Encoding.UTF8.GetString(data); } catch (Exception err) { print(err.ToString()); } } }
private string Send(string message) { lock (communicationLock) { // clean all pending messages from receive buffer before sending command while (udpClient.Available > 0) { udpClient.Receive(ref sender); } //Send byte[] commandBytes = Encoding.ASCII.GetBytes(message); udpClient.Send(commandBytes, commandBytes.Length); //Receive byte[] answerBytes = udpClient?.Receive(ref sender); return(Encoding.ASCII.GetString(answerBytes)); } }
private void Receiver() { try { var localPort = int.Parse(LocalPort); _receivingUdpClient = new UdpClient(localPort); IPEndPoint remoteIpEndPoint = null; while (true) { if (_isTimeToExit) { return; } byte[] receiveBytes = _receivingUdpClient?.Receive(ref remoteIpEndPoint); if (receiveBytes != null && ContainHead(receiveBytes, out int index)) { if (receiveBytes.Length >= Footbot.MaxIncomePacketLenght) { _receiveTimeout.Restart(); byte[] incomeData = new byte[Footbot.MaxIncomePacketLenght]; Array.Copy(receiveBytes, index, incomeData, 0, incomeData.Length); var incomeValues = Footbot.getStruct(incomeData); BarrierState = incomeValues.BarrierState; Q0 = incomeValues.Q0; Q1 = incomeValues.Q1; Q2 = incomeValues.Q2; Q3 = incomeValues.Q3; Ip = incomeValues.Ip; Voltage = incomeValues.Voltage; LeftX = incomeValues.LeftX; LeftY = incomeValues.LeftY; RightX = incomeValues.RightX; RightY = incomeValues.RightY; KickerChargeStatus = incomeValues.KickerChargeStatus; } } Thread.Sleep(10); } } catch (Exception ex) { Console.WriteLine("Возникло исключение: " + ex.ToString() + "\n " + ex.Message); } }
// Update is called once per frame void ReceiveData() { client = new UdpClient (port); while (true) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); byte[] data = client.Receive(ref anyIP); string text = Encoding.UTF8.GetString(data); string[] delimiters = {", ", ","}; texts = text.Split(delimiters,StringSplitOptions.None); } catch(Exception e) { Debug.LogError (e.ToString()); } } }
[MethodImpl(MethodImplOptions.AggressiveInlining)] //関数のインライン展開を積極的にやってもらう. private void ReadingMethod() { IPEndPoint ipEP = new IPEndPoint(IPAddress.Any, 0); try { byte[] ba = UCR?.Receive(ref ipEP); if (disposing) { return; } _ = Task.Run(ReadingMethod); //再帰的 DataReceived(ba, ipEP); } catch (ObjectDisposedException) { Console.WriteLine("udpcom ::: ReadingMethod => ObjectDisposed."); } }
static void Main(string[] args) { //Setup UDP client int listenport = 9000; UdpClient listener = new UdpClient (listenport); Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //Initialize ip and command from args IPAddress sendIP = IPAddress.Parse (args[0]); string sendCommand = args[1]; //Send command byte[] sendbuf = Encoding.ASCII.GetBytes (sendCommand); IPEndPoint sendEP = new IPEndPoint (sendIP, listenport); s.SendTo (sendbuf, sendEP); //Wait for answer and output to console byte[] bytes = listener.Receive (ref sendEP); Console.WriteLine (Encoding.ASCII.GetString (bytes, 0, bytes.Length)); }
public void Execute() { Thread listManager = null; try { //join muticast and listen at 64537 port udpServer = new UdpClient(Utilities.multicastEndPoint.Port); udpServer.JoinMulticastGroup(Utilities.multicastEndPoint.Address); //create thread to manage userlist listManager = new Thread(this.ListManager); listManager.Start(); //wait for data or for closeServerUDP while (true) { while (udpServer.Available == 0 && !closeServerUDP) { //wait for 0,1 seconds Thread.Sleep(100); } if (!closeServerUDP && udpServer.Available > 0) { //Datagram received and put it into temp list IPEndPoint RemoteIpEndPoint = new IPEndPoint(0, 0); byte[] data = udpServer.Receive(ref RemoteIpEndPoint); queue.Enqueue(new Tuple <byte[], IPEndPoint>(data, RemoteIpEndPoint)); newData.Set(); } else if (closeServerUDP) { //if closeServerUDP is true exit break; } } //leave multicast group and close udpclient (finally) udpServer.DropMulticastGroup(Utilities.multicastEndPoint.Address); udpServer.Close(); //close ListSetter listManager.Join(); } catch (Exception e) { Console.WriteLine(e.ToString()); //close socket if (udpServer != null && udpServer.Client != null) { udpServer.Close(); } //close listManager CloseThread(); if (listManager != null) { listManager.Join(); } //say to settingsform that you closed settingsForm.BeginInvoke(settingsForm.CloseThreadDelegate, new object[] { Thread.CurrentThread, Utilities.ServerUDP }); } }
/* * Receive audio data coming on port 1550 and feed it to the speakers to be played. */ public void Receive() { //TODO: Receive Sound DATA try { byte[] byteData; bStop = false; IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); cGlobalVars.AddLogChat("Client Audio Connected"); while (!bStop) { //Receive data. try { //bytes_received = udp_socket.ReceiveFrom(data, ref ep); try { byteData = udpClient.Receive(ref remoteEP); } catch (Exception) { return; } //G711 compresses the data by 50%, so we allocate a buffer of double //the size to store the decompressed data. byte[] byteDecodedData = new byte[byteData.Length * 2]; if (vocoder == VoiceCommon.Vocoder.ALaw) { ALawDecoder.ALawDecode(byteData, out byteDecodedData); //Vocoder.ALaw } else if (vocoder == VoiceCommon.Vocoder.uLaw) { MuLawDecoder.MuLawDecode(byteData, out byteDecodedData); //Vocoder.uLaw } else { byteDecodedData = new byte[byteData.Length]; byteDecodedData = byteData; } bwp_internet.AddSamples(byteData, 0, byteData.Length); } catch (Exception) { } } cGlobalVars.AddLogChat("Client Audio Disconnected"); } catch (Exception ex) { cGlobalVars.AddLogChat("Voice Receive > " + ex.Message); //MessageBox.Show(ex.Message, "VoiceChat-Receive ()", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { nUdpClientFlag += 1; } }
public void Listen() { while (true) { string receivedData = ""; try { receivedData = GetString(ClientHandler.Receive(ref EndPoint)); } catch (Exception e) { Disconnect(); } string[] datas = receivedData.Split('|'); if (!isConnected) { return; } if (receivedData.StartsWith("OK|")) // Connection success { CConsole.addMessage("Connection succeed to " + EndPoint.ToString() + " (" + receivedData.Replace("OK|", "") + ")!"); timerSendInfo = new Timer(new TimerCallback(SendServerInformations), null, 1000, tickRate); } else if (receivedData.StartsWith("JOIN|")) // New player { int id = Int32.Parse(datas[1]); if (listPlayers.ContainsKey(id)) { PlayerDisconnected(id); } CPlayer newPlayer = new CPlayer(id, datas[2], (Vector3)ExtractDataFromString(datas[3], SentData.Vector3)); listPlayers.Add(id, newPlayer); } else if (receivedData.StartsWith("SETINFO|")) // New player { int ID; if (Int32.TryParse(datas[1], out ID) && listPlayers.ContainsKey(ID)) { listPlayers[ID].SetNewPos((Vector3)ExtractDataFromString(datas[2], SentData.Vector3), (Vector3)ExtractDataFromString(datas[3], SentData.Vector3)); listPlayers[ID].SetCrouched((bool)ExtractDataFromString(datas[4], SentData.Bool)); listPlayers[ID].gunId = (int)ExtractDataFromString(datas[5], SentData.Int); listPlayers[ID].SetJump((bool)ExtractDataFromString(datas[6], SentData.Bool)); listPlayers[ID].SetReload((bool)ExtractDataFromString(datas[8], SentData.Bool)); listPlayers[ID].SetShot((bool)ExtractDataFromString(datas[9], SentData.Bool)); listPlayers[ID].SetSwitch((bool)ExtractDataFromString(datas[10], SentData.Bool)); listPlayers[ID].SetWalk((bool)ExtractDataFromString(datas[11], SentData.Bool)); if (listPlayers[ID].botController._selectedWeap != listPlayers[ID].gunId) { listPlayers[ID].botController._selectedWeap = listPlayers[ID].gunId; } } } else if (receivedData.StartsWith("QUIT|")) // Server message { int ID; if (Int32.TryParse(datas[1], out ID)) { PlayerDisconnected(ID); } } else if (receivedData.StartsWith("ECHO|")) // Server message { CConsole.addMessage("Server: " + receivedData.Replace("ECHO|", "")); } else if (receivedData.StartsWith("PLGOTHIT|")) { int ID; if (Int32.TryParse(datas[1], out ID) && listPlayers.ContainsKey(ID)) { listPlayers[ID].ReceiveHit((int)ExtractDataFromString(datas[3], SentData.Int), datas[2]); } } else if (receivedData.StartsWith("UGOTHIT|")) { int ID; if (Int32.TryParse(datas[1], out ID) && listPlayers.ContainsKey(ID)) { CConsole._Character._life -= (int)ExtractDataFromString(datas[3], SentData.Int); } } } }
private void StartWebRtcRtpListener(IceCandidate iceCandidate) { string localEndPoint = "?"; try { localEndPoint = iceCandidate.LocalRtpSocket.LocalEndPoint.ToString(); logger.Debug("Starting WebRTC RTP listener for call " + CallID + " on socket " + localEndPoint + "."); IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); UdpClient localSocket = new UdpClient(); localSocket.Client = iceCandidate.LocalRtpSocket; while (!IsClosed) { try { //logger.Debug("ListenToReceiverWebRTCClient Receive."); byte[] buffer = localSocket.Receive(ref remoteEndPoint); iceCandidate.LastCommunicationAt = DateTime.Now; //logger.Debug(buffer.Length + " bytes read on Receiver Client media socket from " + remoteEndPoint.ToString() + "."); //if (buffer.Length > 3 && buffer[0] == 0x16 && buffer[1] == 0xfe) if (buffer[0] >= 20 && buffer[0] <= 64) { //OnMediaPacket(iceCandidate, buffer, remoteEndPoint); if (OnDtlsPacket != null) { OnDtlsPacket(iceCandidate, buffer, remoteEndPoint); } } //else if ((buffer[0] & 0x80) == 0) else if (buffer[0] == 0 || buffer[0] == 1) { STUNv2Message stunMessage = STUNv2Message.ParseSTUNMessage(buffer, buffer.Length); ProcessStunMessage(iceCandidate, stunMessage, remoteEndPoint); } else { if (OnMediaPacket != null) { OnMediaPacket(iceCandidate, buffer, remoteEndPoint); } } } catch (Exception sockExcp) { _communicationFailureCount++; logger.Warn("Exception ListenToReceiverWebRTCClient Receive (" + localEndPoint + " and " + remoteEndPoint + ", failure count " + _communicationFailureCount + "). " + sockExcp.Message); // Need to be careful about deciding when the connection has failed. Sometimes the STUN requests we send will arrive before the remote peer is ready and cause a socket exception. // Only shutdown the peer if we are sure all ICE intialisation is complete and the socket exception occurred after the RTP had stated flowing. if (iceCandidate.IsStunLocalExchangeComplete && iceCandidate.IsStunRemoteExchangeComplete && iceCandidate.RemoteRtpEndPoint != null && remoteEndPoint != null && iceCandidate.RemoteRtpEndPoint.ToString() == remoteEndPoint.ToString() && DateTime.Now.Subtract(IceNegotiationStartedAt).TotalSeconds > 10) { logger.Warn("WebRtc peer communication failure on call " + CallID + " for local RTP socket " + localEndPoint + " and remote RTP socket " + remoteEndPoint + " ."); iceCandidate.DisconnectionMessage = sockExcp.Message; break; } else if (_communicationFailureCount > COMMUNICATION_FAILURE_COUNT_FOR_CLOSE) { logger.Warn("WebRtc peer communication failures on call " + CallID + " exceeded limit of " + COMMUNICATION_FAILURE_COUNT_FOR_CLOSE + " closing peer."); break; } //else if (DateTime.Now.Subtract(peer.IceNegotiationStartedAt).TotalSeconds > ICE_CONNECTION_LIMIT_SECONDS) //{ // logger.Warn("WebRTC peer ICE connection establishment timed out on call " + peer.CallID + " for " + iceCandidate.LocalRtpSocket.LocalEndPoint + "."); // break; //} } } Close(); } catch (Exception excp) { logger.Error("Exception ListenForWebRTCClient (" + localEndPoint + "). " + excp); } }
/// <summary> /// The compile. /// </summary> /// <param name="asset"> /// The asset. /// </param> /// <param name="platform"> /// The platform. /// </param> public void Compile(EffectAsset asset, TargetPlatform platform) { var announceString = Encoding.ASCII.GetBytes("request compiler"); var targetAddress = IPAddress.None; var client = new UdpClient(4321); client.Client.ReceiveTimeout = 500; try { client.Send(announceString, announceString.Length, new IPEndPoint(IPAddress.Broadcast, 4321)); } catch (SocketException) { Console.WriteLine("WARNING: Unable to locate remote compiler for effect compilation."); return; } var endpoint = new IPEndPoint(IPAddress.Loopback, 4321); try { var bytes = client.Receive(ref endpoint); while (Encoding.ASCII.GetString(bytes) == "request compiler") { bytes = client.Receive(ref endpoint); } if (Encoding.ASCII.GetString(bytes) == "provide compiler") { targetAddress = endpoint.Address; } else { Console.WriteLine("WARNING: Received unexpected message from " + endpoint + " when locating remote effect compiler."); return; } } catch { Console.WriteLine("WARNING: Unable to locate remote compiler for effect compilation."); return; } // Connect to the target on port 80. var webClient = new WebClient(); try { var result = webClient.UploadData("http://" + targetAddress + ":8080/compileeffect?platform=" + (int)platform, Encoding.ASCII.GetBytes(asset.Code)); asset.PlatformData = new PlatformData { Platform = platform, Data = result }; } catch (WebException ex) { using (var reader = new StreamReader(ex.Response.GetResponseStream())) { throw new InvalidOperationException(reader.ReadToEnd()); } } try { asset.ReloadEffect(); } catch (NoAssetContentManagerException) { } }
public void ReceiveUDP() { try { //Open the Kinect Process procKinect = new Process(); path = path.Replace("/Assets", ""); UnityEngine.Debug.Log(path); ProcessStartInfo info = new ProcessStartInfo(path); procKinect = Process.Start(info); Thread.Sleep(1000); SetFocusOnROCHE(); ToggleKWindow(); // Kinect launched. Do upd call. kinectLaunched = true; udpc = new UdpClient("127.0.0.1", 2055); Thread.Sleep(1000); // while bucle while (Thread.CurrentThread.IsAlive) { //we can send a 'request' string if we want string name = "RH"; byte[] sdata = Encoding.ASCII.GetBytes(name); udpc.Send(sdata, sdata.Length); // Receive data byte[] rdata = udpc.Receive(ref ep); currentPacket = Encoding.ASCII.GetString(rdata); // There's no packet, sleep for a bit if (currentPacket == null || currentPacket == "null") { Thread.Sleep(20); } else { string[] coords = currentPacket.Split('-'); currentHandUsed = Convert.ToString(coords[0]); if (currentHandUsed == "r") { GetRightHandInput(coords); leftHand.Reset(); } else if (currentHandUsed == "l") { GetLeftHandInput(coords); rightHand.Reset(); } } Thread.Sleep(5); } } catch (Exception ex) { ReleaseEverything(); UnityEngine.Debug.Log(ex.Message); } }
/* * Prati odometriju */ public static void Work() { Byte[] sendBytes; Byte[] receiveBytes; Byte[] sbuf; IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); //udpClient.Send(sendBytes, sendBytes.Length); //IPEndPoint object will allow us to read datagrams sent from any source. // Blocks until a message returns on this socket from a remote host. // = udpClient.Receive(ref RemoteIpEndPoint); //string returnData = Encoding.ASCII.GetString(receiveBytes); // Uses the IPEndPoint object to determine which of these two hosts responded. //Console.WriteLine("This is the message you received " + returnData.ToString()); //Console.WriteLine("This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString()); //Console.WriteLine("pLevo: " + (plevo).ToString() + "\t= "); //Console.WriteLine("pDesno:" + (pdesno).ToString() + "\t= "); ////Console.WriteLine("UgaoL: " + ((plevo - levo) / 3.1).ToString()); ////Console.WriteLine("UgaoD: " + (((pdesno - desno)) / 3.1).ToString()); //Console.WriteLine("---------------------------------------------"); //Console.WriteLine("mLevo: " + (plevo - levo).ToString() + "\t= " + ((plevo - levo) * 1.34 / 1000).ToString() + "m"); //Console.WriteLine("mDesno:" + (pdesno - desno).ToString() + "\t= " + ((pdesno - desno) * 1.34 / 1000).ToString() + "m"); //Console.WriteLine("mUgaoL: " + ((plevo - levo) / 3.1).ToString()); //Console.WriteLine("mUgaoD: " + (((pdesno - desno)) / 3.1).ToString()); /* while (true) * {*/ sendBytes = Encoding.ASCII.GetBytes("data"); udpClient.Send(sendBytes, sendBytes.Length); sbuf = udpClient.Receive(ref RemoteIpEndPoint); System.Threading.Thread.Sleep(100); levo = ((((long)sbuf[8] << 24)) + (((long)sbuf[7] << 16)) + (((long)sbuf[6] << 8)) + ((long)sbuf[5])) - greska; desno = ((((long)sbuf[16] << 24)) + (((long)sbuf[15] << 16)) + (((long)sbuf[14] << 8)) + ((long)sbuf[13])) - greska; //Console.WriteLine("Levo: " + (levo).ToString()); //Console.WriteLine("Desno:" + (desno).ToString()); //stavljamo trenutni kao pocetni //plevo = lLevo; // = lDesno; //180995 - 153718 //returnData = Encoding.ASCII.GetString(receiveBytes); //Console.Clear(); //Console.WriteLine(String.Format("X:{0} Y:{1} theta:{2}", current_position.x, current_position.y, current_position.theta * 180 / PI)); left_ticks = plevo - levo; right_ticks = pdesno - desno; plevo = levo; pdesno = desno; //Console.WriteLine("ticks L:" + left_ticks); //Console.WriteLine("ticks R:" + right_ticks); dist_left = (double)left_ticks * MUL_COUNT; dist_right = (double)right_ticks * MUL_COUNT; //Console.WriteLine("distance L:" + dist_left); //Console.WriteLine("distance R:" + dist_right); cos_current = System.Math.Cos(current_position.theta); sin_current = System.Math.Sin(current_position.theta); current_position.x = System.Math.Round(current_position.x, 3); current_position.y = System.Math.Round(current_position.y, 3); if (System.Math.Abs(left_ticks - right_ticks) <= 10) { /* Moving in a straight line */ current_position.x += System.Math.Round(dist_left * cos_current, 3); current_position.y += System.Math.Round(dist_left * sin_current, 3); } else { /* Moving in an arc */ expr1 = AXLE_LENGTH * (dist_right + dist_left) / 2.0 / (dist_right - dist_left); right_minus_left = dist_right - dist_left; current_position.x += System.Math.Round(expr1 * (System.Math.Sin(right_minus_left / AXLE_LENGTH + current_position.theta) - sin_current), 3); current_position.y -= System.Math.Round(expr1 * (System.Math.Cos(right_minus_left / AXLE_LENGTH + current_position.theta) - cos_current), 3); /* Calculate new orientation */ current_position.theta += right_minus_left / AXLE_LENGTH; /*Keep in the range -PI to +PI */ while (current_position.theta > PI) { current_position.theta -= (2.0 * PI); } while (current_position.theta < -PI) { current_position.theta += (2.0 * PI); } /* while (current_position.theta > 2*PI) * current_position.theta = 0; * while (current_position.theta < 0) * current_position.theta = 2.0 * PI;*/ } System.Threading.Thread.Sleep(delay); //} }
// Update is called once per frame void Update() { if (inclient.Available > 0) { byte[] data = inclient.Receive(ref inremoteEndPoint); scenario = System.BitConverter.ToDouble(data, 0); } Debug.Log(scenario); if (scenario != prevScenario) { prevScenario = scenario; if (scenario == 0) { //Switch off everything transform.localPosition = Vector3.zero; transform.localScale = Vector3.zero; propellers.MuteAll(); movement.move = false; } else { if (scenario == 1) { //Posn A transform.localPosition = startPosnA; } else if (scenario == 2) { //Posn B transform.localPosition = startPosnB; } else if (scenario == 3) { //Posn C transform.localPosition = startPosnC; } transform.localScale = droneScale * Vector3.one; propellers.UnmuteAll(); movement.move = true; } } byte[] outdata = new byte[28]; byte[] vxout = new byte[4]; byte[] vyout = new byte[4]; byte[] vzout = new byte[4]; byte[] dxout = new byte[4]; byte[] dyout = new byte[4]; byte[] dzout = new byte[4]; byte[] startout = new byte[4]; vxout = System.BitConverter.GetBytes(movement.vx); vyout = System.BitConverter.GetBytes(movement.vy); vzout = System.BitConverter.GetBytes(movement.vz); dxout = System.BitConverter.GetBytes(transform.localPosition.x - mainCamera.transform.localPosition.x); dyout = System.BitConverter.GetBytes(transform.localPosition.z - mainCamera.transform.localPosition.z); dzout = System.BitConverter.GetBytes(transform.localPosition.y - mainCamera.transform.localPosition.y); startout = System.BitConverter.GetBytes(1.0f); System.Buffer.BlockCopy(vxout, 0, outdata, 0, 4); System.Buffer.BlockCopy(vyout, 0, outdata, 4, 4); System.Buffer.BlockCopy(vzout, 0, outdata, 8, 4); System.Buffer.BlockCopy(dxout, 0, outdata, 12, 4); System.Buffer.BlockCopy(dyout, 0, outdata, 16, 4); System.Buffer.BlockCopy(dzout, 0, outdata, 20, 4); System.Buffer.BlockCopy(startout, 0, outdata, 24, 4); sendSocket.SendTo(outdata, sendEndPoint); }
void receiveData() { receiveBytes = udpClient.Receive(ref ep); }
void ToOpen() { var ip = UDP_type_multicast.IsChecked ?? false ? IPAddress.Any : UDP_Local_ip.Ip; var mport = UDP_Local_port.Port; if (!mport.HasValue) { return; } int port = mport.Value; try { var uc = new UdpClient(new IPEndPoint(ip, port)); socket = uc; port = ((IPEndPoint)uc.Client.LocalEndPoint).Port; MsgBox.LogSystem($"Open on {{ {ip} :{port} }}"); SetEnables(); uc.EnableBroadcast = UDP_type_broadcast.IsChecked ?? false; if (UDP_type_broadcast.IsChecked ?? false) { MsgBox.LogSystem($"Enabled Broadcast on {{ {UDP_Target_ip.Ip} }}"); } if (UDP_type_multicast.IsChecked ?? false) { var mip = UDP_multicast_ip.Text.ParseIp(); sendClients = new List <UdpClient>(); var msgs = (from networkInterface in NetworkInterface.GetAllNetworkInterfaces() where networkInterface.OperationalStatus == OperationalStatus.Up select networkInterface.GetIPProperties() .UnicastAddresses.First(addr => addr.Address.AddressFamily == AddressFamily.InterNetwork)?.Address) .Where(address => address != null) .Select(addr => { uc.JoinMulticastGroup(mip, addr); sendClients.Add(new UdpClient(new IPEndPoint(addr, port))); return($"Join Multicast Group {{ {mip} on {addr} }}"); }); MsgBox.LogSystem(msgs.ToArray()); //uc.JoinMulticastGroup(mip); //LogSystem($"Join Multicast Group {{ {mip} }}"); } loop = new CancellationTokenSource(); loops.Add(Task.Run(() => { while (socket != null || socket != uc) { try { var ep = new IPEndPoint(IPAddress.Any, 0); var buffer = uc.Receive(ref ep); var str = Encoding.Default.GetString(buffer); MsgBox.Log(ep, str, true); } catch (Exception ex) { if (socket == null || socket != uc) { MsgBox.LogSystem("Closed"); } else { MsgBox.LogError(ex); } return; } } }, loop.Token)); } catch (Exception ex) { MsgBox.LogError(ex); return; } }
private void Listen() { try { UdpClient udpSvr = m_udpListener; if (udpSvr == null) { logger.LogError("The UDP server was not correctly initialised in the RTP sink when attempting to start the listener, the RTP stream has not been intialised."); return; } else { logger.LogDebug("RTP Listener now listening on " + m_localEndPoint.Address + ":" + m_localEndPoint.Port + "."); } IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] rcvdBytes = null; m_startRTPReceiveTime = DateTime.MinValue; m_lastRTPReceivedTime = DateTime.MinValue; DateTime previousRTPReceiveTime = DateTime.MinValue; uint previousTimestamp = 0; UInt16 sequenceNumber = 0; UInt16 previousSeqNum = 0; uint senderSendSpacing = 0; uint lastSenderSendSpacing = 0; while (!StopListening) { rcvdBytes = null; try { rcvdBytes = udpSvr.Receive(ref remoteEndPoint); } catch { //logger.LogWarning("Remote socket closed on receive. Last RTP received " + m_lastRTPReceivedTime.ToString("dd MMM yyyy HH:mm:ss") + ", last RTP successfull send " + m_lastRTPSentTime.ToString("dd MMM yyyy HH:mm:ss") + "."); } if (rcvdBytes != null && rcvdBytes.Length > 0) { // Check whether this is an RTCP report. UInt16 firstWord = BitConverter.ToUInt16(rcvdBytes, 0); if (BitConverter.IsLittleEndian) { firstWord = NetConvert.DoReverseEndian(firstWord); } ushort packetType = 0; if (BitConverter.IsLittleEndian) { packetType = Convert.ToUInt16(firstWord & 0x00ff); } if (packetType == RTCPHeader.RTCP_PACKET_TYPE) { logger.LogDebug("RTP Listener received remote RTCP report from " + remoteEndPoint + "."); try { RTCPPacket rtcpPacket = new RTCPPacket(rcvdBytes); RTCPReportPacket rtcpReportPacket = new RTCPReportPacket(rtcpPacket.Reports); if (RTCPReportReceived != null) { RTCPReportReceived(this, rtcpReportPacket); } } catch (Exception rtcpExcp) { logger.LogError("Exception processing remote RTCP report. " + rtcpExcp.Message); } continue; } // Channel statistics. DateTime rtpReceiveTime = DateTime.Now; if (m_startRTPReceiveTime == DateTime.MinValue) { m_startRTPReceiveTime = rtpReceiveTime; //m_sampleStartTime = rtpReceiveTime; } previousRTPReceiveTime = new DateTime(m_lastRTPReceivedTime.Ticks); m_lastRTPReceivedTime = rtpReceiveTime; m_packetsReceived++; m_bytesReceived += rcvdBytes.Length; previousSeqNum = sequenceNumber; // This stops the thread running the ListenerTimeout method from deciding the strema has recieved no RTP and therefore should be shutdown. m_lastPacketReceived.Set(); // Let whoever has subscribed that an RTP packet has been received. if (DataReceived != null) { try { DataReceived(m_streamId, rcvdBytes, remoteEndPoint); } catch (Exception excp) { logger.LogError("Exception RTPSink DataReceived. " + excp.Message); } } if (m_packetsReceived % 500 == 0) { logger.LogDebug("Total packets received from " + remoteEndPoint.ToString() + " " + m_packetsReceived + ", bytes " + NumberFormatter.ToSIByteFormat(m_bytesReceived, 2) + "."); } try { RTPPacket rtpPacket = new RTPPacket(rcvdBytes); uint syncSource = rtpPacket.Header.SyncSource; uint timestamp = rtpPacket.Header.Timestamp; sequenceNumber = rtpPacket.Header.SequenceNumber; //logger.LogDebug("seqno=" + rtpPacket.Header.SequenceNumber + ", timestamp=" + timestamp); if (previousRTPReceiveTime != DateTime.MinValue) { //uint senderSendSpacing = rtpPacket.Header.Timestamp - previousTimestamp; // Need to cope with cases where the timestamp has looped, if this timestamp is < last timesatmp and there is a large difference in them then it's because the timestamp counter has looped. lastSenderSendSpacing = senderSendSpacing; senderSendSpacing = (Math.Abs(timestamp - previousTimestamp) > (uint.MaxValue / 2)) ? timestamp + uint.MaxValue - previousTimestamp : timestamp - previousTimestamp; if (previousTimestamp > timestamp) { logger.LogError("BUG: Listener previous timestamp (" + previousTimestamp + ") > timestamp (" + timestamp + "), last seq num=" + previousSeqNum + ", seqnum=" + sequenceNumber + "."); // Cover for this bug until it's nailed down. senderSendSpacing = lastSenderSendSpacing; } double senderSpacingMilliseconds = (double)senderSendSpacing / (double)TIMESTAMP_FACTOR; double interarrivalReceiveTime = m_lastRTPReceivedTime.Subtract(previousRTPReceiveTime).TotalMilliseconds; #region RTCP reporting. if (m_rtcpSampler == null) { //resultslogger.LogInformation("First Packet: " + rtpPacket.Header.SequenceNumber + "," + m_arrivalTime.ToString("HH:mm:fff")); m_rtcpSampler = new RTCPReportSampler(m_streamId, syncSource, remoteEndPoint, rtpPacket.Header.SequenceNumber, m_lastRTPReceivedTime, rcvdBytes.Length); m_rtcpSampler.RTCPReportReady += new RTCPSampleReadyDelegate(m_rtcpSampler_RTCPReportReady); m_rtcpSampler.StartSampling(); } else { //m_receiverReports[syncSource].RecordRTPReceive(rtpPacket.Header.SequenceNumber, sendTime, rtpReceiveTime, rcvdBytes.Length); // Transit time is calculated by knowing that the sender sent a packet at a certain time after the last send and the receiver received a pakcet a certain time after the last receive. // The difference in these two times is the jitter present. The transit time can change with each transimission and as this methid relies on two sends two packet // arrivals to calculate the transit time it's not going to be perfect (you'd need synchronised NTP clocks at each end to be able to be accurate). // However if used tor an average calculation it should be pretty close. //double transitTime = Math.Abs(interarrivalReceiveTime - senderSpacingMilliseconds); uint jitter = (interarrivalReceiveTime - senderSpacingMilliseconds > 0) ? Convert.ToUInt32(interarrivalReceiveTime - senderSpacingMilliseconds) : 0; if (jitter > 75) { logger.LogDebug("seqno=" + rtpPacket.Header.SequenceNumber + ", timestmap=" + timestamp + ", ts-prev=" + previousTimestamp + ", receive spacing=" + interarrivalReceiveTime + ", send spacing=" + senderSpacingMilliseconds + ", jitter=" + jitter); } else { //logger.LogDebug("seqno=" + rtpPacket.Header.SequenceNumber + ", receive spacing=" + interarrivalReceiveTime + ", timestamp=" + timestamp + ", transit time=" + transitTime); } m_rtcpSampler.RecordRTPReceive(m_lastRTPReceivedTime, rtpPacket.Header.SequenceNumber, rcvdBytes.Length, jitter); } #endregion } else { logger.LogDebug("RTPSink Listen SyncSource=" + rtpPacket.Header.SyncSource + "."); } previousTimestamp = timestamp; } catch (Exception excp) { logger.LogError("Received data was not a valid RTP packet. " + excp.Message); } #region Switching endpoint if required to cope with NAT. // If a packet is recieved from an endpoint that wasn't expected treat the stream as being NATted and switch the endpoint to the socket on the NAT server. try { if (m_streamEndPoint != null && m_streamEndPoint.Address != null && remoteEndPoint != null && remoteEndPoint.Address != null && (m_streamEndPoint.Address.ToString() != remoteEndPoint.Address.ToString() || m_streamEndPoint.Port != remoteEndPoint.Port)) { logger.LogDebug("Expecting RTP on " + IPSocket.GetSocketString(m_streamEndPoint) + " but received on " + IPSocket.GetSocketString(remoteEndPoint) + ", now sending to " + IPSocket.GetSocketString(remoteEndPoint) + "."); m_streamEndPoint = remoteEndPoint; if (RemoteEndPointChanged != null) { try { RemoteEndPointChanged(m_streamId, remoteEndPoint); } catch (Exception changeExcp) { logger.LogError("Exception RTPListener Changing Remote EndPoint. " + changeExcp.Message); } } } } catch (Exception setSendExcp) { logger.LogError("Exception RTPListener setting SendTo Socket. " + setSendExcp.Message); } #endregion } else if (!StopListening) // Empty packet was received possibly indicating connection closure so check for timeout. { double noRTPRcvdDuration = (m_lastRTPReceivedTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPReceivedTime).TotalSeconds : 0; double noRTPSentDuration = (m_lastRTPSentTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPSentTime).TotalSeconds : 0; //logger.LogWarning("Remote socket closed on receive on " + m_localEndPoint.Address.ToString() + ":" + + m_localEndPoint.Port + ", reinitialising. No rtp for " + noRTPRcvdDuration + "s. last rtp " + m_lastRTPReceivedTime.ToString("dd MMM yyyy HH:mm:ss") + "."); // If this check is not done then the stream will never time out if it doesn't receive the first packet. if (m_lastRTPReceivedTime == DateTime.MinValue) { m_lastRTPReceivedTime = DateTime.Now; } remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); if ((noRTPRcvdDuration > NO_RTP_TIMEOUT || noRTPSentDuration > NO_RTP_TIMEOUT) && StopIfNoData) { logger.LogWarning("Disconnecting RTP listener on " + m_localEndPoint.ToString() + " due to not being able to send or receive any RTP for " + NO_RTP_TIMEOUT + "s."); Shutdown(); } } } } catch (Exception excp) { logger.LogError("Exception Listen RTPSink: " + excp.Message); } finally { #region Shut down socket. Shutdown(); if (ListenerClosed != null) { try { ListenerClosed(m_streamId, m_callDescriptorId); } catch (Exception excp) { logger.LogError("Exception RTPSink ListenerClosed. " + excp.Message); } } #endregion } }
public void HandleRequests() { var endPoint = new IPEndPoint(IPAddress.Any, networkPort); while (true) { var requestBytes = udpServer.Receive(ref endPoint); var request = Encoding.UTF8.GetString(requestBytes); var response = "ERROR"; //process the request //if login request, check username and password if (Regex.Match(request, @"^LOGIN,[A-Za-z]+,[A-Za-z0-9]+$").Success) { string[] requestArray = request.Split(','); using (var context = new NetworkedCheckersContainer()) { var query = from user in context.Users select user; foreach (var user in query) { if (requestArray[1].Equals(user.UserName) && requestArray[2].Equals(user.Password) && user.LoginStatus == false) { user.LoginStatus = true; //create string of online users string allUser = ""; foreach (var userObj in query) { if (userObj.LoginStatus == true) { allUser += userObj.UserName; allUser += ":"; } } allUser = allUser.Remove(allUser.Length - 1); BroadcastMessages("USERS," + allUser); response = "OKAY"; break; } } context.SaveChanges(); } } //if logoff request else if (Regex.Match(request, @"^LOGOUT,[A-Za-z]+$").Success) { string[] requestArray = request.Split(','); using (var context = new NetworkedCheckersContainer()) { var query = from user in context.Users select user; foreach (var user in query) { //change the login status of the designated user to false if (user.UserName == requestArray[1] && user.LoginStatus == true) { user.LoginStatus = false; break; } } context.SaveChanges(); //create string of online users string allUser = ""; foreach (var user in query) { if (user.LoginStatus == true) { allUser += user.UserName; allUser += ":"; } } if (allUser != "") { allUser = allUser.Remove(allUser.Length - 1); } BroadcastMessages("USERS," + allUser); response = "OKAY"; } } else { switch (gamestate) { case GameState.WAIT_FOR_GAME_START: if (Regex.Match(request, @"^PLAY,[A-Za-z]+,[A-Za-z]+$").Success) { string[] requestArray = request.Split(','); p1Name = requestArray[1]; p2Name = requestArray[2]; if (p1Name != p2Name) { //set move count to 0 gameMoveCount = 0; //set board to initial position board.resetBoard(); gamestate = GameState.Player1_MOVING; BroadcastMessages("GAMESTATE," + board.GetPieces()); BroadcastMessages("GAMESTART," + p1Name + "," + p2Name); BroadcastMessages("STATUS," + p1Name + ",MOVING"); BroadcastMessages("STATUS," + p2Name + ",WAITING"); response = "OKAY"; } } break; case GameState.Player1_MOVING: if (Regex.Match(request, @"^TRY,[A-Za-z]+,[1-8][1-8],[1-8][1-8]$").Success) { string[] requestArray = request.Split(','); //check whether this is the player's turn to move if (requestArray[1].Equals(p1Name)) { //check whether the move is valid if (board.IsValidMovePlayer1(requestArray[2] + "," + requestArray[3])) { //move the piece board.Move(requestArray[2], requestArray[3], Piece.PLAYER1); gameMoveCount++; BroadcastMessages("GAMESTATE," + board.GetPieces()); BroadcastMessages("STATUS," + p2Name + ",MOVING"); BroadcastMessages("STATUS," + p1Name + ",WAITING"); response = "DONE"; //check whether the player win after the move if (board.isP1Win()) { gamestate = GameState.GAME_OVER; Record("Game Over. Player 1 Wins"); BroadcastMessages("STATUS," + p1Name + ",WON"); BroadcastMessages("STATUS," + p2Name + ",LOST"); using (var context = new NetworkedCheckersContainer()) { //identify the winning user from database var p1User = from user in context.Users where user.UserName.Equals(p1Name) select user; //add new highscore to Highscores table var highscore = new Highscore() { DateTime = DateTime.Now.ToString(), MoveCount = (Int16)gameMoveCount, User = p1User.First() }; context.Highscores.Add(highscore); context.SaveChanges(); } showLeaderBoard(); } else { gamestate = GameState.Player2_MOVING; } } } } break; case GameState.Player2_MOVING: if (Regex.Match(request, @"^TRY,[A-Za-z]+,[1-8][1-8],[1-8][1-8]$").Success) { //check whether this is the player's turn to move string[] requestArray = request.Split(','); if (requestArray[1].Equals(p2Name)) { //check whether the move is valid if (board.IsValidMovePlayer2(requestArray[2] + "," + requestArray[3])) { //move the piece board.Move(requestArray[2], requestArray[3], Piece.PLAYER2); gameMoveCount++; BroadcastMessages("GAMESTATE," + board.GetPieces()); BroadcastMessages("STATUS," + p1Name + ",MOVING"); BroadcastMessages("STATUS," + p2Name + ",WAITING"); response = "DONE"; //check whether the player win after the move if (board.isP2Win()) { gamestate = GameState.GAME_OVER; Record("Game Over. Player 2 Wins"); BroadcastMessages("STATUS," + p2Name + ",WON"); BroadcastMessages("STATUS," + p1Name + ",LOST"); //record the win into the database using (var context = new NetworkedCheckersContainer()) { //identify the winning user from database var p2User = from user in context.Users where user.UserName.Equals(p2Name) select user; //add new highscore to Highscores table var highscore = new Highscore() { DateTime = DateTime.Now.ToString(), MoveCount = (Int16)gameMoveCount, User = p2User.First() }; context.Highscores.Add(highscore); context.SaveChanges(); } showLeaderBoard(); } else { gamestate = GameState.Player1_MOVING; } } } } break; case GameState.GAME_OVER: if (Regex.Match(request, @"^PLAY,[A-Za-z]+,[A-Za-z]+$").Success) { gamestate = GameState.WAIT_FOR_GAME_START; goto case GameState.WAIT_FOR_GAME_START; } break; } } //send response var responseBytes = Encoding.UTF8.GetBytes(response); udpServer.Send(responseBytes, responseBytes.Length, endPoint); Record("Request: " + request); Record("Response: " + response); Record("New Game State: " + gamestate.ToString()); Record("Current Game State: " + gamestate.ToString()); } }
private static void runServer(string name, int port) { try { IPEndPoint addr = new IPEndPoint(IPAddress.Any, DEFAULT_PORT_REQUEST); client = new UdpClient(); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.ExclusiveAddressUse = false; client.Client.Bind(addr); Log.debug("LAN Discovery: Starting to listen"); running = true; while (running) { IPEndPoint other = null; byte[] bytes = client.Receive(ref other); if (bytes.Length < MAGIC.Length + 1) { continue; } Log.debug("LAN Discovery: Received a request from " + other); bool okay = true; for (int i = 0; i < MAGIC.Length; ++i) { if (bytes[i] != MAGIC[i]) { okay = false; break; } } if (!okay) { Log.debug("LAN Discovery: Bad magic"); continue; } if (bytes[MAGIC.Length] != Multiplayer.PROTOCOL_VERSION) { Log.debug("LAN Discovery: Bad protocol version (" + (int)bytes[MAGIC.Length] + " vs " + (int)Multiplayer.PROTOCOL_VERSION + ")"); continue; } Log.debug("LAN Discovery: Preparing and sending response"); byte[] portBytes = BitConverter.GetBytes(port); byte[] nameBytes = Encoding.ASCII.GetBytes(name); byte[] sendBack = new byte[MAGIC.Length + portBytes.Length + nameBytes.Length]; Array.Copy(MAGIC, 0, sendBack, 0, MAGIC.Length); Array.Copy(portBytes, 0, sendBack, MAGIC.Length, portBytes.Length); Array.Copy(nameBytes, 0, sendBack, MAGIC.Length + portBytes.Length, nameBytes.Length); other.Port = DEFAULT_PORT_RESPONSE; UdpClient sendFrom = new UdpClient(); sendFrom.Send(sendBack, sendBack.Length, new IPEndPoint(IPAddress.Parse("10.0.2.15"), DEFAULT_PORT_RESPONSE)); sendFrom.Close(); } } catch (Exception e) { if (e is SocketException && (((SocketException)e).Message.IndexOf("A blocking operation was interrupted") != -1 || ((SocketException)e).Message.IndexOf("WSACancelBlockingCall") != -1)) { return; } Log.error("Exception during LAN discovery: " + e); } finally { if (client != null) { client.Close(); client = null; } } }
/// <summary> /// Background thread handling all incoming traffic /// </summary> private void ReceivePackets() { while (true) { try { // Get a datagram receiveFrom = new IPEndPoint(IPAddress.Any, localPort); // Stopwatch sw = new Stopwatch(); // sw.Start(); byte[] data = udpClientReceive.Receive(ref receiveFrom); //if (sw.ElapsedMilliseconds > 10) { Console.WriteLine(sw.ElapsedMilliseconds); } //sw.Stop(); // Decode the message Stream stream = new MemoryStream(data); IBencodingType receivedMsg = BencodingUtils.Decode(stream); string decoded = BencodingUtils.ExtendedASCIIEncoding.GetString(data.ToArray()); //Log("Received message!"); // t is transaction id // y is e for error, r for reply, q for query if (receivedMsg is BDict) // throws error.. todo: fix { BDict dictMsg = (BDict)receivedMsg; if (dictMsg.ContainsKey("y")) { if (dictMsg["y"].Equals(new BString("e"))) { //Log("Received error! (ignored)"); } else if (dictMsg["y"].Equals(new BString("r"))) { // received reply if (dictMsg.ContainsKey("r")) { if (dictMsg["r"] is BDict) { BDict dictMsg2 = (BDict)dictMsg["r"]; if (dictMsg2.ContainsKey("values")) { //Log("Received list of peers for torrent!"); countRecvPeerPackets++; } else if (dictMsg2.ContainsKey("nodes")) { // could be an answer to find node or get peers //Log("Received list of nodeID & IP & port!"); countRecvNodePackets++; BString nodeIDString = (BString)dictMsg2["nodes"]; UpdateContactList(nodeIDString); } else { // no values and no nodes, assuming its a ping, // at least some form of response } } else { } } } else if (dictMsg["y"].Equals(new BString("q"))) { // received query countRecvQuery++; //Log("Received query! (ignored)"); } } } } catch (Exception ex) { //Log("Error receiving data: " + ex.ToString()); } } }
static void Main(string[] args) { bool exit = false; while (!exit) { string myFileName = String.Format("{0}__{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "data" + ".txt"); // string myFullPath = System.IO.Path.Combine("C:\\Users\\Tom.Maclean\\source\\repos\\XPlaneReader\\XPlaneReader", myFileName); string myFullPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, myFileName); byte[] data = new byte[1024]; string headings = "Time | N/A | N/A | N/A | N/A | N/A | N/A | _Vind,_kias | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | elev,stick | ailrn,stick | ruddr,stick | N/A | N/A | N/A | N/A | N/A | N/A | ___Q,rad/s | ___P,rad/s | ___R,rad/s | N/A | N/A | N/A | N/A | N/A | N/A | pitch,__deg | _roll,__deg | N/A | hding,__mag | N/A | N/A | N/A | N/A | N/A | N/A | _beta,__deg | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | __alt,ftmsl | N/A | N/A | N/A | N/A | N/A | N/A | thro1,_part | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | trq_1,ftlb | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | rpm_1,_prop | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | ptch1,__deg | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N1__1,_pcnt | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N2__1,_pcnt | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | FF_1,__galh | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | ITT_1,__deg | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | v-spd,__fpm | N/A | N/A | N/A | N/A | N/A | N/A |"; System.IO.File.WriteAllText(myFullPath, headings); Console.WriteLine("X-Plane Data Read: \n"); Console.WriteLine("Press any key to start recording \n\n"); Console.ReadKey(true); // int i = 0 // while (i < 10) while (Console.KeyAvailable == false) { IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 49005); UdpClient newsock = new UdpClient(ipep); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 49005); data = newsock.Receive(ref sender); for (int index = 5; index < data.Length; index++) // Skip first five characters "DATA*" { // Console.Write("{0},", data[index]); } string DecimalToHex = BitConverter.ToString(data).Replace("-", ""); // Convert to hex output using (System.IO.StreamWriter file = new System.IO.StreamWriter(myFullPath, true)) { file.WriteLine(""); } for (int index = 34; index < DecimalToHex.Length; index = index + 8) // Skip first five characters "DATA*" (10) and first two useless times (3*8) { string HexRep = DecimalToHex.Substring(index, 8); //Convert to hex but now need to change from DCBA to ABCD char[] phraseAsChars = HexRep.ToCharArray(); char[] endianChar = new char[8]; endianChar[0] = phraseAsChars[6]; endianChar[1] = phraseAsChars[7]; endianChar[2] = phraseAsChars[4]; endianChar[3] = phraseAsChars[5]; endianChar[4] = phraseAsChars[2]; endianChar[5] = phraseAsChars[3]; endianChar[6] = phraseAsChars[0]; endianChar[7] = phraseAsChars[1]; string HexActual = new string(endianChar); Int32 IntRep = Int32.Parse(HexActual, NumberStyles.AllowHexSpecifier); // Integer to Byte[] and presenting it for float conversion float f = BitConverter.ToSingle(BitConverter.GetBytes(IntRep), 0); // There you go using (System.IO.StreamWriter file = new System.IO.StreamWriter(myFullPath, true)) { file.Write(f.ToString("N3")); file.Write(" | "); } Console.Write("{0}", f); Console.Write(" | "); } Console.Write("\n"); // i++; newsock.Close(); Thread.Sleep(100); // Wait 100ms (10 outputs per second) } Console.WriteLine("\n The file has been saved as:"); Console.WriteLine(myFileName); Console.WriteLine("Press the spacebar to record again, or any other key to quit \n\n\n\n"); Console.ReadKey(true); ConsoleKeyInfo checkQuit; checkQuit = Console.ReadKey(true); if (checkQuit.Key == ConsoleKey.Spacebar) { exit = false; } else { exit = true; } } }
public static byte[] ReceiveRaw() { IPEndPoint Sender = new IPEndPoint(IPAddress.Any, Port); return(UDP.Receive(ref Sender)); }
private static void runClient() { try { IPEndPoint addr = new IPEndPoint(IPAddress.Any, DEFAULT_PORT_RESPONSE); client = new UdpClient(); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.ExclusiveAddressUse = false; client.Client.Bind(addr); running = true; while (running) { IPEndPoint other = null; byte[] bytes = client.Receive(ref other); if (bytes.Length < MAGIC.Length + 5) { continue; } Log.debug("LAN Discovery: Received a response from " + other); bool okay = true; for (int i = 0; i < MAGIC.Length; ++i) { if (bytes[i] != MAGIC[i]) { okay = false; break; } } if (!okay) { Log.debug("LAN Discovery: Bad magic"); continue; } Log.debug("LAN Discovery: Valid LAN discovery found."); byte[] nameBytes = new byte[bytes.Length - MAGIC.Length - 4]; Array.Copy(bytes, MAGIC.Length + 4, nameBytes, 0, nameBytes.Length); int port = BitConverter.ToInt16(bytes, MAGIC.Length); string name = Encoding.ASCII.GetString(nameBytes); if (onDiscovery != null) { onDiscovery.Invoke(name, other, port); } } } catch (Exception e) { if (e is SocketException && (((SocketException)e).Message.IndexOf("A blocking operation was interrupted") != -1 || ((SocketException)e).Message.IndexOf("WSACancelBlockingCall") != -1)) { return; } Log.error("Exception during LAN discovery: " + e); } finally { if (client != null) { client.Close(); client = null; } } }
public static void LRMStart(List <String[]> switchTables) { string received_data; byte[] receive_byte_array; string[] returnvalues = null; string label1 = null; string label2 = null; string port1 = null; string port2 = null; string connectionid = null; string SNPPs = null; try { while (true) { receive_byte_array = listener.Receive(ref groupEP); received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length); Router.RouterMain.WriteLine("LRM: Otrzymano:\t" + received_data); string[] splitArray = received_data.Split('_'); //wiadomość od CC if (splitArray[0].Equals("LinkConnectionRequest")) { connectionid = received_data.Split('*')[1]; SNPPs = splitArray[1].Split('*')[0]; Thread lcr = new Thread(() => { returnvalues = LinkConnectionRequest(splitArray[1].Split('*')[0], switchTables, labelpool, nextlrms); label2 = returnvalues[0]; port1 = returnvalues[1]; port2 = returnvalues[2]; if (returnvalues.Length == 4) { label1 = returnvalues[3]; } if (label1 != null && label2 != null) { LinkConnection(port1, label1, port2, label2, switchTables, connectionid); label1 = null; label2 = null; port1 = null; port2 = null; Send("LinkConnectionRequestConfirm_" + routernumber + "*" + connectionid, ccport); Router.RouterMain.WriteLine("LRM: Zestawiono połączenie nr " + connectionid); } }); lcr.Start(); } //wiadomośc od CC (jeszcze nie gotowe) else if (splitArray[0].Equals("LinkConnectionDeallocation")) { LinkConnectionDeallocation(switchTables, splitArray[1]); } //wiadomośc od wcześniejszego LRMa else if (splitArray[0].Equals("LinkConnection")) { Send("LinkConnectionConfirmation", splitArray[2]); Router.RouterMain.WriteLine("LRM: Wysłano potwierdzenie otrzymania wiadomości z etykietą " + splitArray[1] + " na port zwrotny " + splitArray[2]); label1 = splitArray[1]; } else if (splitArray[0].Equals("BreakConnection")) { Router.RouterMain.WriteLine("LRM: Zerwano połączenie pomiędzy interfejsem " + splitArray[1].Split('/')[1] + " routera " + splitArray[1].Split('.')[0] + " i interfejsem " + splitArray[2].Split('/')[1] + " routera " + splitArray[2].Split('.')[0] + "."); Send(received_data, rcport); Router.RouterMain.WriteLine("LRM: Wysłano informację o zerwanym łączu do RC na port " + rcport); Send("BreakConnection_" + " " + "*" + connectionid, ccport); Router.RouterMain.WriteLine("LRM: Wysłano informację o zerwanym łączu do CC na port " + ccport); Send(received_data, "14099"); } else if (splitArray[0].Equals("RestoreConnection")) { Router.RouterMain.WriteLine("LRM: Naprawiono połączenie pomiędzy interfejsem " + splitArray[1].Split('/')[1] + " routera " + splitArray[1].Split('.')[0] + " i interfejsem " + splitArray[2].Split('/')[1] + " routera " + splitArray[2].Split('.')[0] + "."); Send(received_data, rcport); Router.RouterMain.WriteLine("LRM: Wysłano informację o naprawionym łączu do RC na port " + rcport); Send("RestoreConnection_" + " " + "*" + connectionid, ccport); Router.RouterMain.WriteLine("LRM: Wysłano informację o naprawionym łączu do CC na port " + ccport); Send(received_data, "14099"); } //warunek pozwalający zestawić połączenie czyli dodać linijkę do tablicy komutacji if (label1 != null && label2 != null) { LinkConnection(port1, label1, port2, label2, switchTables, connectionid); label1 = null; label2 = null; port1 = null; port2 = null; Send("LinkConnectionRequestConfirm_" + routernumber + "*" + connectionid, ccport); Router.RouterMain.WriteLine("LRM: Zestawiono połączenie nr " + connectionid); } } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
private void ListenForPackets() { while (true) { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] bytes = null; try { bytes = _udpClient.Receive(ref RemoteIpEndPoint); BasicTunnelPacket packet = StandardUdpPacketFactory.instance.getPacket(bytes, RemoteIpEndPoint); if (packet.type == BasicTunnelPacket.PKT_TYPE_WAVE_RS) { #if (DEBUG) Logger.Debug("Got a wave response from " + packet.ip + ", my address is " + ((StandardWaveTunnelRsPacket)packet).externalEndPoint + "/" + ((StandardWaveTunnelRsPacket)packet).internalEndPoint); #endif ProcessWaveRs((StandardWaveTunnelRsPacket)packet); Logger.Debug("Shutting down wave listener"); break; } else { Logger.Error("Waiting for a wave response, but got unknown packet"); break; } } catch (SocketException e) { #if (DEBUG) Logger.Debug("Caught a socket exception [" + e.ErrorCode + "] : " + e.Message); #endif if (e.ErrorCode == 10004) // Interrupted { #if (DEBUG) Logger.Debug("Socket has been interrupted, shutting down"); #endif _udpClient.Close(); break; } else if (e.ErrorCode == 10054) // Got ICMP connection closed ( we need to ignore this, hole punching causes these during init ) { #if (DEBUG) Logger.Debug("Remote host stated ICMP port closed, ignoring"); #endif } else { Logger.Warn("Caught a socket exception [" + e.ErrorCode + "], this looks spurious, ignoring : " + e.Message); Logger.Error("Caught a socket exception [" + e.ErrorCode + "], shutting down read thread : " + e.Message); _udpClient.Close(); break; } } catch (ThreadAbortException e) { #if DEBUG Logger.Debug("Thread is aborting, closing : " + e.Message); #endif _udpClient.Close(); break; } catch (Exception e) { Logger.Error("Exception while reading from UDP socket, shutting down read thread : " + e.Message, e); // Most likely the link has failed (this side) or the app is closing // either way, close the thread for the moment _udpClient.Close(); break; } } }
private void StartSearching(object sender, RoutedEventArgs e) { if (searching != null && searching.IsAlive) { searching.Interrupt(); udpSearching.Close(); SearchBtn.Content = "Поиск..."; } else { Devices.Items.Clear(); searching = new Thread(() => { try { Dictionary <Tuple <int, String>, ServerInfo> ServerSet = new Dictionary <Tuple <int, String>, ServerInfo>(); udpSearching = new UdpClient(Session.BroadcastingPort); IPEndPoint ip = null; while (true) { byte[] data = udpSearching.Receive(ref ip); string message = Encoding.UTF8.GetString(data); Server server = JsonConvert.DeserializeObject <Server>(message); Tuple <int, String> serverTuple = new Tuple <int, string>(server.type, server.name); if (!ServerSet.ContainsKey(serverTuple)) { Thread searching2 = new Thread(() => { try { while (true) { foreach (Tuple <int, string> p in ServerSet.Keys.ToList()) { if (ServerSet[p].value > 0) { ServerSet[p].value--; } Application.Current.Dispatcher.Invoke(new Action(() => { if (ServerSet[p].value <= 0) { ServerSet[p].lvi.Visibility = Visibility.Collapsed; } else if (ServerSet[p].lvi != null) { ServerSet[p].lvi.Visibility = Visibility.Visible; } })); } Thread.Sleep(2000); } }catch (ThreadInterruptedException _) { } }); searching2.Start(); ServerInfo si = new ServerInfo(); Application.Current.Dispatcher.Invoke(new Action(() => { StackPanel sp = new StackPanel(); sp.Margin = new Thickness(10); sp.Orientation = Orientation.Horizontal; PackIcon pi = new PackIcon(); pi.Foreground = new SolidColorBrush(Colors.White); pi.Kind = server.kind == 0 ? PackIconKind.Smartphone : PackIconKind.Computer; pi.Height = pi.Width = 40; TextBlock tb = new TextBlock(); tb.Text = server.name + '\n' + Session.decodeType(server.type); tb.Foreground = new SolidColorBrush(Colors.White); tb.FontSize = 15; tb.Padding = new Thickness(10, 0, 0, 0); sp.Children.Add(pi); sp.Children.Add(tb); ListViewItem lvi = new ListViewItem(); lvi.Content = sp; Devices.Items.Add(lvi); si.lvi = lvi; lvi.Selected += delegate { searching.Interrupt(); searching2.Interrupt(); udpSearching.Close(); SearchBtn.Content = "Поиск..."; lvi.Visibility = Visibility.Collapsed; SessionClient sessionClient = new SessionClient(ip.Address, server.port, server.type, server.mode); }; })); ServerSet.Add(serverTuple, si); } else { ServerSet[serverTuple].value = 5; } } } catch (System.Net.Sockets.SocketException) { } }); searching.Start(); SearchBtn.Content = "Остановить поиск"; } }
private void ProcessDatagrams(object state) { UdpClient listener = (UdpClient)state; while (true) { // Check if we already closed the server if (listener.Client == null) { return; } // WSAECONNRESET: // The virtual circuit was reset by the remote side executing a hard or abortive close. // The application should close the socket; it is no longer usable. On a UDP-datagram socket // this error indicates a previous send operation resulted in an ICMP Port Unreachable message. // Note the spocket settings on creation of the server. It makes us ignore these resets. IPEndPoint senderEndpoint = null; try { //var result = listener.ReceiveAsync().Result; //senderEndpoint = result.RemoteEndPoint; //receiveBytes = result.Buffer; Byte[] receiveBytes = listener.Receive(ref senderEndpoint); Interlocked.Exchange(ref ServerInfo.AvailableBytes, listener.Available); Interlocked.Increment(ref ServerInfo.NumberOfPacketsInPerSecond); Interlocked.Add(ref ServerInfo.TotalPacketSizeIn, receiveBytes.Length); if (receiveBytes.Length != 0) { _receiveThreadPool.QueueUserWorkItem(() => { try { if (!GreylistManager.IsWhitelisted(senderEndpoint.Address) && GreylistManager.IsBlacklisted(senderEndpoint.Address)) { return; } if (GreylistManager.IsGreylisted(senderEndpoint.Address)) { return; } ProcessMessage(receiveBytes, senderEndpoint); } catch (Exception e) { Log.Warn($"Process message error from: {senderEndpoint.Address}", e); } }); } else { Log.Warn("Unexpected end of transmission?"); continue; } } catch (Exception e) { Log.Error("Unexpected end of transmission?", e); if (listener.Client != null) { continue; } return; } } }
private void FuncRcvData() { client = new UdpClient (port); client.Client.ReceiveTimeout = 300; // msec client.Client.Blocking = false; while (stopThr == false) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); string text = Encoding.ASCII.GetString(data); lastRcvd = text; if (lastRcvd.Length > 0) { Thread.Sleep(delay_msec); client.Send(data, data.Length, anyIP); // echo } } catch (Exception err) { // print(err.ToString()); } // without this sleep, on adnroid, the app will not start (freeze at Unity splash) Thread.Sleep(20); // 200 } client.Close (); }