// 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());
            }
        }
    }
Exemple #2
1
    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);
          }
    }
Exemple #3
0
    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();
        }
    }
Exemple #4
0
 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;
 }
	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());
			}
		}
	}
Exemple #6
0
 void Start()
 {
     client = new UdpClient(listenPort);
     client.Connect(scHostname,scPort);
     Send("/notify", 1);
     StartCoroutine( Listen() );
 }
	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
			}
		}
	}
Exemple #8
0
 public async Task ConnectAsync_IPAddressHost_Success()
 {
     using (var c = new UdpClient())
     {
         await c.Client.ConnectAsync(IPAddress.Parse("114.114.114.114"), 53);
     }
 }
Exemple #9
0
 public void init()
 {
     IP = "192.168.15.11";
     port = 8051;
     remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
     client = new UdpClient();
 }
Exemple #10
0
	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 void exportData(ref UdpClient client, ref IPEndPoint anyIP)
    {
        byte[] data;
        string text;

        text = "SOT"; // start of table
        text = text + System.Environment.NewLine;
        data = System.Text.Encoding.ASCII.GetBytes(text);
        client.Send(data, data.Length, anyIP);

        foreach (var ptr in timeGraphScript.dateTime_val_dic) {
            text = ptr.Key.ToString("yyyy/MM/dd HH:mm:ss");
            text = text + ",";
            text = text + ptr.Value.ToString();
            text = text + System.Environment.NewLine;

            data = System.Text.Encoding.ASCII.GetBytes(text);
            client.Send(data, data.Length, anyIP);
        }

        text = "EOT"; // end of table
        text = text + System.Environment.NewLine;
        data = System.Text.Encoding.ASCII.GetBytes(text);
        client.Send(data, data.Length, anyIP);
    }
    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 ();
    }
 public static void WakeUp(byte[] mac, string ip = "255.255.255.255", int port = 9)
 {
     using (var client = new UdpClient {EnableBroadcast = true})
     {
         client.Send(CreateMagickPacket(mac), MagickPacketSize, ip, port);
     }
 }
 public void LoadClient()
 {
     client = new UdpClient(System.Convert.ToInt32(port));
         receivePoint = new IPEndPoint(IPAddress.Parse(ip),System.Convert.ToInt32(port));
         Thread startClient = new Thread(new ThreadStart(start_client));
         startClient.Start();
 }
Exemple #16
0
    public bool Connect()
    {
        try
        {

            serverRemote = new IPEndPoint(IPAddress.Parse(ipAddress), portNumber);
            udpClient = new UdpClient();
            udpClient.Connect(serverRemote);
            if(udpClient.Client.Connected)
            {
                Debug.Log("connected!");
                sendUDPPacket("ANYONE OUT THERE?");

            //byte[] data = Encoding.UTF8.GetBytes(toSend);

            //client.Send(data, data.Length, serverRemote);
            //client.SendTimeout(serverRemote, data);

            }

        }
        catch(Exception ex)
        {
            print ( ex.Message + " : OnConnect");
        }
        isConnected = true;
        if ( udpClient == null ) return false;
        return udpClient.Client.Connected;
    }
Exemple #17
0
    //private CIPC_CS_Unity.CLIENT.CLIENT CIPCclient;
    //private Thread thred;
    //private FPSAdjuster.FPSAdjuster fps;
    // Use this for initialization
    

    void Start()
    {
        if (this.renderTexture == null )
        {
            return;
        }
        this.client = new UdpClient();
        this.sendtexture = new Texture2D(this.renderTexture.width, this.renderTexture.height);

        if (this.portNumber == 0)
        {
            this.portNumber = 15000;
        }
        //if (this.serverPort == 0)
        //{
        //    this.serverPort = 50000;
        //}
        if (this.IPAdress == "")
        {
            this.IPAdress = "127.0.0.1";
        }
        
        
        //this.CIPCclient = new CIPC_CS_Unity.CLIENT.CLIENT(this.portNumber, this.IPAdress, this.serverPort);
        //this.CIPCclient.Setup(CIPC_CS_Unity.CLIENT.MODE.Sender);

        //this.fps = new FPSAdjuster.FPSAdjuster();
        //this.fps.Fps = 30;
        //this.fps.Start();
        //this.thred = new Thread (new ThreadStart(this.sendimage));
        //this.thred.Start();
    }
Exemple #18
0
    private static void SendMes(string datagram)
    {
        // Создаем UdpClient
        UdpClient sender = new UdpClient();

        // Создаем endPoint по информации об удаленном хосте
        IPEndPoint endPoint = new IPEndPoint(remoteIPAddress, remotePort);

        try
        {
            // Преобразуем данные в массив байтов
            byte[] bytes = Encoding.UTF8.GetBytes(datagram);

            // Отправляем данные
            sender.Send(bytes, bytes.Length, endPoint);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Возникло исключение: " + ex.ToString() + "\n  " + ex.Message);
        }
        finally
        {
            // Закрыть соединение
            sender.Close();
        }
    }
Exemple #19
0
 //public Program()
 //{
 //    socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 //    localEP = new IPEndPoint(IPAddress.Any,port);
 //    socket.Bind(localEP);
 //    ConnectionEstablished = false;
 //}
 public Program()
 {
     localEP = new IPEndPoint(IPAddress.Any, port);
     server = new UdpClient(localEP);
     //IPEndPoint
     //client.Send()
 }
 public UDPListener(int listen_port)
 {
     this.listen_port = listen_port;
     done = false;
     listener = new UdpClient(listen_port);
     groupEP = new IPEndPoint(IPAddress.Any, listen_port);
 }
        public void messageReceiver()
        {
            UdpClient activeListener = new UdpClient(receivingPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, receivingPort);
            string received_data;
            byte[] receive_byte_array;
            try
            {
                while (true)
                {
                    receive_byte_array = activeListener.Receive(ref groupEP);
                    received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
                    string[] holster = received_data.Split(',');
                    string username = holster[0];
                    string ip = holster[1];
                    userSemaphore.WaitOne();
                    usernames.Add(username);
                    ips.Add(ip);
                    userSemaphore.Release();
                }
            }
            catch (Exception e)
            {

            }
        }
Exemple #22
0
        // Connect for receiving messages
        public bool Connect(int localPort)
        {
            Disconnect();
            receiveDone.Reset();
            // Connect to a local port.
            try
            {
                localEP = new IPEndPoint(IPAddress.Any, localPort);

                // Create a UDP Client.
                clientReceive = new UdpClient(localEP);

                if (ConnectedStateChanged != null) ConnectedStateChanged(this, new ConnectedStateChangedEventArgs(true));

                // Setup the receiver client thread
                receiverTask = new Thread(ReceiverLoop);
                receiverTask.Start();

                // Signal that the connection has been made.
                connectDone.Set();
            }
            catch (Exception e)
            {
                Disconnect();
                //
                Console.WriteLine(e.ToString());
            }

            return IsConnected;
        }
Exemple #23
0
 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();
     }
 }
    //受信スレッド
    private void ReceiveData()
    {
        //udpクライアント設定
        udpClient = new UdpClient(port);

        while(threadAvairable)
        {
            try
            {
                if(udpClient.Available > 0)
                {
                    IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    byte[] data = udpClient.Receive(ref ipEndPoint);

                    recievedDataStr = Encoding.UTF8.GetString(data);
                    isDataRecieved = true;
                }
            }
            catch(Exception err)
            {
                Debug.LogError(err.Message);
                DebugConsole.LogError(err.Message);
                break;
            }
        }
    }
Exemple #25
0
 public async Task ConnectAsync_StringHost_Success()
 {
     using (var c = new UdpClient())
     {
         await c.Client.ConnectAsync("114.114.114.114", 53);
     }
 }
Exemple #26
0
 void OnDestroy()
 {
     if (udpClient != null) {
       udpClient.Close();
       udpClient = null;
     }
 }
Exemple #27
0
   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();
   }
    // init
    public void init(string targetIP, string name)
    {
        playerName = name;
        GameObject.FindGameObjectWithTag("Game").GetComponent<Canvas>().enabled = true;
        GameObject.FindGameObjectWithTag("GUI").GetComponent<Canvas>().enabled = false;
        print("UDPSend.init()");
        port = 8051;
        IPAddress[] addrs = Dns.GetHostEntry(Dns.GetHostName()).AddressList;

        foreach (var ip in addrs)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                playerIP = ip.ToString();
            }
        }

        remoteEndPoint = new IPEndPoint(IPAddress.Parse(targetIP), port);
        client = new UdpClient();
        connected = true;

        // status
        print("Sending to " + targetIP + " : " + port);
        print("Player IP is " + playerIP);
    }
 void Start()
 {
     server = new UdpClient(port);
     isReceiving = true;
     Data = string.Empty;
     StartCoroutine("ReceiverStart");
 }
	// receive thread
	private  void ReceiveData() {

		client = new UdpClient(port);
		while (true) {

			try {
				// Bytes empfangen.
				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);

				// Den abgerufenen Text anzeigen.
				print(">> " + text);

				// latest UDPpacket
				lastReceivedUDPPacket=text;

				// ....
				allReceivedUDPPackets=allReceivedUDPPackets+text;

			}
			catch (Exception err) {
				print(err.ToString());
			}
		}
	}
 void Start()
 {
     Assert.IsNotNull(handler, "should set handler.");
     endPoint_ = new IPEndPoint(IPAddress.Any, listenPort);
     udpClient_ = new UdpClient(endPoint_);
 }
Exemple #32
0
        public async void StartSwarmChain()
        {
            var exepath = CheckandGetSITLImage("ArduCopter.elf");
            var model   = "+";

            var config = await GetDefaultConfig(model);

            var max = 10.0;

            if (InputBox.Show("how many?", "how many?", ref max) != DialogResult.OK)
            {
                return;
            }

            max--;

            for (int a = (int)max; a >= 0; a--)
            {
                var extra = " --disable-fgview -r50";

                if (!string.IsNullOrEmpty(config))
                {
                    extra += @" --defaults """ + config + @""" -P SERIAL0_PROTOCOL=2 -P SERIAL1_PROTOCOL=2 ";
                }

                var home = new PointLatLngAlt(markeroverlay.Markers[0].Position).newpos((double)NUM_heading.Value, a * 4);

                if (max == a)
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "", a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }
                else
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "--uartD tcpclient:127.0.0.1:" + (5772 + 10 * a), a + 1,
                        BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }

                string simdir = sitldirectory + model + (a + 1) + Path.DirectorySeparatorChar;

                Directory.CreateDirectory(simdir);

                string path = Environment.GetEnvironmentVariable("PATH");

                Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path,
                                                   EnvironmentVariableTarget.Process);

                Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

                ProcessStartInfo exestart = new ProcessStartInfo();
                exestart.FileName         = await exepath;
                exestart.Arguments        = extra;
                exestart.WorkingDirectory = simdir;
                exestart.WindowStyle      = ProcessWindowStyle.Minimized;
                exestart.UseShellExecute  = true;

                File.AppendAllText(Settings.GetUserDataDirectory() + "sitl.bat",
                                   "mkdir " + (a + 1) + "\ncd " + (a + 1) + "\n" + @"""" + exepath + @"""" + " " + extra + " &\n");

                File.AppendAllText(Settings.GetUserDataDirectory() + "sitl1.sh",
                                   "mkdir " + (a + 1) + "\ncd " + (a + 1) + "\n" + @"""../" +
                                   Path.GetFileName(await exepath).Replace("C:", "/mnt/c").Replace("\\", "/").Replace(".exe", ".elf") + @"""" + " " +
                                   extra.Replace("C:", "/mnt/c").Replace("\\", "/") + " &\nsleep .3\ncd ..\n");

                Process.Start(exestart);
            }

            try
            {
                var client = new Comms.TcpSerial();

                client.client = new TcpClient("127.0.0.1", 5760);

                MainV2.comPort.BaseStream = client;

                SITLSEND = new UdpClient("127.0.0.1", 5501);

                Thread.Sleep(200);

                MainV2.instance.doConnect(MainV2.comPort, "preset", "5760");

                return;
            }
            catch
            {
                CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                return;
            }
        }
Exemple #33
0
        public async Task Execute(CancellationToken cancellationToken, IProgress <double> progress)
        {
            // Parse string to byte array
            int port = Plugin.Instance.Configuration.WakeOnLanPort;

            byte[]   mac        = null;
            string[] macDigits  = null;
            string   macAddress = Plugin.Instance.Configuration.HostMacAddress;

            if (macAddress.Contains("-"))
            {
                macDigits = macAddress.Split('-');
            }
            else
            {
                macDigits = macAddress.Split(':');
            }

            if (macDigits.Length != 6)
            {
                this.logger.Warn("Incorrect MAC address");
                return;
            }
            else
            {
                mac = macDigits.Select(s => Convert.ToByte(s, 16)).ToArray();
            }


            this.logger.Info($"Waking on MAC: {BitConverter.ToString(mac)}");

            int counter = 0;

            byte[] bytes = new byte[6 * 17];
            for (var i = 0; i < 6; i++)
            {
                bytes[counter++] = 0xFF;
            }

            //16x MAC
            for (var i = 0; i < 16; i++)
            {
                mac.CopyTo(bytes, 6 + i * 6);
            }

            progress.Report(5);
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                using (var client = new UdpClient())
                {
                    client.EnableBroadcast = true;
                    await client.SendAsync(bytes, bytes.Length, new IPEndPoint(new IPAddress(0xffffffff), port))
                    .WithCancellation(cancellationToken)
                    .ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                this.logger.ErrorException($"Exception during wake on lan request.", ex);
            }

            progress.Report(100);
        }
Exemple #34
0
 public static byte[] receive(UdpClient client, IPEndPoint point)
 {
     byte[] response = client.Receive(ref point);
     return(response);
 }
Exemple #35
0
        public void Listen()
        {
            _udpLastReceived = 0;
            _ready           = false;
            _listener        = new UdpClient();
            try
            {
                _listener.AllowNatTraversal(true);
            }
            catch { }
            // _listener.Connect(_serverEndpoint);

            //start 2 audio processing threads
            var decoderThread = new Thread(UdpAudioDecode);

            decoderThread.Start();

            var settings = GlobalSettingsStore.Instance;

            _inputManager.StartDetectPtt(pressed =>
            {
                var radios = _clientStateSingleton.DcsPlayerRadioInfo;

                var radioSwitchPtt          = _globalSettings.ProfileSettingsStore.GetClientSettingBool(ProfileSettingsKeys.RadioSwitchIsPTT);
                var radioSwitchPttWhenValid = _globalSettings.ProfileSettingsStore.GetClientSettingBool(ProfileSettingsKeys.RadioSwitchIsPTTOnlyWhenValid);

                //store the current PTT state and radios
                var currentRadioId = radios.selected;
                var currentPtt     = _ptt;

                var ptt = false;
                foreach (var inputBindState in pressed)
                {
                    if (inputBindState.IsActive)
                    {
                        //radio switch?
                        if ((int)inputBindState.MainDevice.InputBind >= (int)InputBinding.Intercom &&
                            (int)inputBindState.MainDevice.InputBind <= (int)InputBinding.Switch10)
                        {
                            //gives you radio id if you minus 100
                            var radioId = (int)inputBindState.MainDevice.InputBind - 100;

                            if (radioId < _clientStateSingleton.DcsPlayerRadioInfo.radios.Length)
                            {
                                var clientRadio = _clientStateSingleton.DcsPlayerRadioInfo.radios[radioId];

                                if (RadioHelper.SelectRadio(radioId))
                                {
                                    //turn on PTT
                                    if (radioSwitchPttWhenValid || radioSwitchPtt)
                                    {
                                        _lastPTTPress = DateTime.Now.Ticks;
                                        ptt           = true;
                                        //Store last release time
                                    }
                                }
                                else
                                {
                                    //turn on PTT even if not valid radio switch
                                    if (radioSwitchPtt)
                                    {
                                        _lastPTTPress = DateTime.Now.Ticks;
                                        ptt           = true;
                                    }
                                }
                            }
                        }
                        else if (inputBindState.MainDevice.InputBind == InputBinding.Ptt)
                        {
                            _lastPTTPress = DateTime.Now.Ticks;
                            ptt           = true;
                        }
                    }
                }

                //if length is zero - no keybinds or no PTT pressed set to false
                var diff = new TimeSpan(DateTime.Now.Ticks - _lastPTTPress);

                //Release the PTT ONLY if X ms have passed and we didnt switch radios to handle
                //shitty buttons
                var releaseTime = _globalSettings.ProfileSettingsStore
                                  .GetClientSetting(ProfileSettingsKeys.PTTReleaseDelay).IntValue;

                if (!ptt &&
                    releaseTime > 0 &&
                    diff.TotalMilliseconds <= releaseTime &&
                    currentRadioId == radios.selected)
                {
                    ptt = true;
                }

                _ptt = ptt;
            });

            StartTimer();

            StartPing();

            _packetNumber = 1; //reset packet number

            while (!_stop)
            {
                if (_ready)
                {
                    try
                    {
                        var groupEp = new IPEndPoint(IPAddress.Any, _port);
                        //   listener.Client.ReceiveTimeout = 3000;

                        var bytes = _listener.Receive(ref groupEp);

                        if (bytes?.Length == 22)
                        {
                            _udpLastReceived = DateTime.Now.Ticks;
                            Logger.Info("Received Ping Back from Server");
                        }
                        else if (bytes?.Length > 22)
                        {
                            _udpLastReceived = DateTime.Now.Ticks;
                            _encodedAudio.Add(bytes);
                        }
                    }
                    catch (Exception e)
                    {
                        //  logger.Error(e, "error listening for UDP Voip");
                    }
                }
            }

            _ready = false;

            //stop UI Refreshing
            _updateTimer.Stop();

            _clientStateSingleton.IsVoipConnected = false;
        }
Exemple #36
0
 protected abstract void Discover(UdpClient client, CancellationToken cancelationToken);
Exemple #37
0
        // -------------------------------------------

        /*
         * Init
         */
        public void Init(int _port)
        {
            m_client = new UdpClient(_port);
        }
        private void IdentificationMe()
        {
            using (UdpClient udpClient = new UdpClient())
            {
                udpClient.EnableBroadcast = true;

                IPEndPoint udpBroadcastPoint = new IPEndPoint(IPAddress.Any, Udp.DefaultPort);
                udpClient.Client.Bind(udpBroadcastPoint);

                while (this.identificationThread.IsAlive)
                {
                    try
                    {
                        TimeSpan     timeToWait = TimeSpan.FromMilliseconds(50);
                        IAsyncResult result     = udpClient.BeginReceive(null, null);
                        result.AsyncWaitHandle.WaitOne(timeToWait);
                        try
                        {
                            IPEndPoint remotePoint = null;
                            byte[]     buffer      = udpClient.EndReceive(result, ref remotePoint);

                            try
                            {
                                RequestPresence requestPresence = Helper.XmlDeserialize <RequestPresence>(Encoding.UTF8.GetString(buffer));

                                Log.WriteLn("Recv: {0} - {1}", requestPresence.Status, remotePoint.Address.ToString());

                                if ("presence".Equals(requestPresence.Status))
                                {
                                    IPEndPointHolder ipEndPointHolder = listOfAvailablePCs.Find(
                                        item => item.IpEndPoint.Address.Equals(IPAddress.Parse(requestPresence.UserAddress.Address)));
                                    if (ipEndPointHolder == null)
                                    {
                                        ipEndPointHolder            = new IPEndPointHolder();
                                        ipEndPointHolder.IpEndPoint = new IPEndPoint(IPAddress.Parse(requestPresence.UserAddress.Address),
                                                                                     requestPresence.UserAddress.Port);
                                        ipEndPointHolder.IsAvailable = true;

                                        listOfAvailablePCs.Add(ipEndPointHolder);
                                        if (UserPresenceReceivedRequest != null)
                                        {
                                            UserPresenceReceivedRequest(requestPresence, ipEndPointHolder);
                                        }
                                    }
                                    else
                                    {
                                        ipEndPointHolder.IsAvailable = true;
                                    }
                                }

                                if ("ask".Equals(requestPresence.Status))
                                {
                                    UserInfo userInfo  = null;
                                    bool     isVisible = true;

                                    if (UserPresenceReceivedAsk != null)
                                    {
                                        UserPresenceReceivedAsk(out isVisible, ref userInfo);
                                    }

                                    if (isVisible)
                                    {
                                        Udp.Send(Helper.XmlSerialize <RequestPresence>(new RequestPresence()
                                        {
                                            Status      = "presence",
                                            UserAddress = new UserAddress()
                                            {
                                                Address = Helper.LocalIPAddress(),
                                                Port    = Udp.DefaultPort
                                            },
                                            UserInfo = userInfo
                                        }), new IPEndPoint(IPAddress.Parse(requestPresence.UserAddress.Address),
                                                           requestPresence.UserAddress.Port));

                                        Log.WriteLn("Send: presence - {0}", requestPresence.UserAddress.Address.ToString());

                                        IPEndPointHolder ipEndPointHolder = listOfAvailablePCs.Find(
                                            item => item.IpEndPoint.Address.Equals(IPAddress.Parse(requestPresence.UserAddress.Address)));
                                        if (ipEndPointHolder == null)
                                        {
                                            Udp.Send(Helper.XmlSerialize <RequestPresence>(new RequestPresence()
                                            {
                                                Status      = "ask",
                                                UserAddress = new UserAddress()
                                                {
                                                    Address = Helper.LocalIPAddress(),
                                                    Port    = Udp.DefaultPort
                                                },
                                                UserInfo = null
                                            }), new IPEndPoint(IPAddress.Parse(requestPresence.UserAddress.Address),
                                                               requestPresence.UserAddress.Port));

                                            Log.WriteLn("Send: ask - {0}", requestPresence.UserAddress.Address.ToString());
                                        }
                                        else
                                        {
                                            ipEndPointHolder.IsAvailable = true;
                                        }
                                    }
                                }

                                if ("left".Equals(requestPresence.Status))
                                {
                                    IPEndPointHolder ipEndPointHolder = listOfAvailablePCs.Find(
                                        item => item.IpEndPoint.Address.Equals(remotePoint.Address));
                                    if (ipEndPointHolder != null)
                                    {
                                        ipEndPointHolder.IsAvailable = false;

                                        if (UserPresenceGotTimeout != null)
                                        {
                                            UserPresenceGotTimeout(ipEndPointHolder);
                                        }

                                        listOfAvailablePCs.Remove(ipEndPointHolder);
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        UserInfo userInfo  = null;
                        bool     isVisible = false;

                        if (UserPresenceReceivedAsk != null)
                        {
                            UserPresenceReceivedAsk(out isVisible, ref userInfo);
                        }

                        foreach (IPEndPointHolder ipEndPointHolder in listOfAvailablePCs)
                        {
                            Udp.Send(Helper.XmlSerialize <RequestPresence>(new RequestPresence()
                            {
                                Status      = "left",
                                UserAddress = new UserAddress()
                                {
                                    Address = Helper.LocalIPAddress(),
                                    Port    = Udp.DefaultPort
                                },
                                UserInfo = null
                            }), ipEndPointHolder.IpEndPoint);

                            Log.WriteLn("Send: left - {0}", ipEndPointHolder.IpEndPoint.Address.ToString());
                        }
                    }
                }
            }
        }
Exemple #39
0
        // End of Method

        //Enable Sender
        private void InitSender()
        {
            SenderClient = new UdpClient(BroadCast, port);
            SenderClient.EnableBroadcast = true;
        }
Exemple #40
0
 /// <summary>
 /// Creates a new instance of the <see cref="UdpState"/> type.
 /// </summary>
 /// <param name="client">The <see cref="UdpClient"/> that will receive messages.</param>
 /// <param name="endPoint">The <see cref="IPEndPoint"/> to listen on.</param>
 internal UdpState(UdpClient client, IPEndPoint endPoint)
 {
     Client   = client;
     EndPoint = endPoint;
 }
Exemple #41
0
        public bool Start()
        {
            var endPoint = Utils.CreateIpEndPoint(_listenOn, 53);

            _stopTokenSource    = new CancellationTokenSource();
            _transactionClients = new ConcurrentDictionary <ushort, IPEndPoint>();
            _transactionTimeoutCancellationTokenSources = new ConcurrentDictionary <ushort, CancellationTokenSource>();
            try
            {
                _udpListener  = new UdpClient(endPoint);
                _udpForwarder = new UdpClient(0);
            }
            catch (SocketException e)
            {
                Logger.Error("[Listener] Failed to start DNSAgent:\n{0}", e);
                Stop();
                return(false);
            }

            _listeningTask = Task.Run(async() =>
            {
                while (!_stopTokenSource.IsCancellationRequested)
                {
                    try
                    {
                        var query = await _udpListener.ReceiveAsync();
                        ProcessMessageAsync(query);
                    }
                    catch (SocketException e)
                    {
                        if (e.SocketErrorCode != SocketError.ConnectionReset)
                        {
                            Logger.Error("[Listener.Receive] Unexpected socket error:\n{0}", e);
                        }
                    }
                    catch (AggregateException e)
                    {
                        var socketException = e.InnerException as SocketException;
                        if (socketException != null)
                        {
                            if (socketException.SocketErrorCode != SocketError.ConnectionReset)
                            {
                                Logger.Error("[Listener.Receive] Unexpected socket error:\n{0}", e);
                            }
                        }
                        else
                        {
                            Logger.Error("[Listener] Unexpected exception:\n{0}", e);
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                    } // Force closing _udpListener will cause this exception
                    catch (Exception e)
                    {
                        Logger.Error("[Listener] Unexpected exception:\n{0}", e);
                    }
                }
            }, _stopTokenSource.Token);

            _forwardingTask = Task.Run(async() =>
            {
                while (!_stopTokenSource.IsCancellationRequested)
                {
                    try
                    {
                        var query = await _udpForwarder.ReceiveAsync();
                        DnsMessage message;
                        try
                        {
                            message = DnsMessage.Parse(query.Buffer);
                        }
                        catch (Exception)
                        {
                            throw new ParsingException();
                        }
                        if (!_transactionClients.ContainsKey(message.TransactionID))
                        {
                            continue;
                        }
                        IPEndPoint remoteEndPoint;
                        CancellationTokenSource ignore;
                        _transactionClients.TryRemove(message.TransactionID, out remoteEndPoint);
                        _transactionTimeoutCancellationTokenSources.TryRemove(message.TransactionID, out ignore);
                        await _udpListener.SendAsync(query.Buffer, query.Buffer.Length, remoteEndPoint);

                        // Update cache
                        if (Options.CacheResponse)
                        {
                            Cache.Update(message.Questions[0], message, Options.CacheAge);
                        }
                    }
                    catch (ParsingException)
                    {
                    }
                    catch (SocketException e)
                    {
                        if (e.SocketErrorCode != SocketError.ConnectionReset)
                        {
                            Logger.Error("[Forwarder.Send] Name server unreachable.");
                        }
                        else
                        {
                            Logger.Error("[Forwarder.Receive] Unexpected socket error:\n{0}", e);
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                    } // Force closing _udpListener will cause this exception
                    catch (Exception e)
                    {
                        Logger.Error("[Forwarder] Unexpected exception:\n{0}", e);
                    }
                }
            }, _stopTokenSource.Token);

            Logger.Info("Listening on {0}...", endPoint);
            OnStarted();
            return(true);
        }
        public void UdpSend(Packet packet, ref UdpClient udpClient)
        {
            byte[] buffer = Serialiser.Serialise(packet);

            udpClient.Send(buffer, buffer.Length, _endPoint);
        }
Exemple #43
0
 public OSC(string ip, int port)
 {
     this.ip   = ip;
     this.port = port;
     server    = new UdpClient(ip, port);
 }
Exemple #44
0
        void SendFunc()
        {
            Sendclient = new UdpClient();
            //发送信息的端口一定要和接受的端口号一样
            SendPort = new IPEndPoint(groupAddress, tport);
            while (true)
            {
                //判断侦听器注册数量
                if (DiscoveryLogServer.Count == 0)
                {
                    ManagerLog("未设置侦听器,无法分拣消息");
                    //LogFile("UDPManager", "未设置侦听器,无法分拣消息");
                    continue;
                }
                try
                {
                    Queue <DataTransfer> datas      = new Queue <DataTransfer>();
                    List <string>        HandleKeys = new List <string>(DiscoveryLogServer.Keys);
                    foreach (string key in HandleKeys)//构建消息队列
                    {
                        List <UDPHandle> tHandle = DiscoveryLogServer[key];
                        if (tHandle == null || tHandle.Count == 0)
                        {
                            //Handle类别为空
                            continue;
                        }
                        DataTransfer transfer = DataTransfer.GetInstance(ID, tHandle[0].HandleType);
                        tHandle.ForEach(delegate(UDPHandle cHandle)
                        {
                            Fields[] tField = cHandle.OnSendData();
                            if (tField == null || tField.Length == 0)
                            {
                                return;
                            }
                            for (int i = 0; i < tField.Length; i++)
                            {
                                tField[i].name = cHandle.HandleName;
                            }
                            transfer.FieldsJoining(tField);
                        });
                        if (transfer.data.Count != 0)
                        {
                            datas.Enqueue(transfer);
                            dataCollections = transfer.ToString();
                        }

                        /*
                         * Fields[] tField = tHandle.OnSendData();
                         * if(tField == null || tField.Length == 0) { continue; }
                         * DataTransfer transfer = DataTransfer.GetInstance(ID, tHandle.HandleType(), tField);
                         * datas.Enqueue(transfer);
                         */
                    }
                    if (datas.Count > 0)
                    {
                        while (datas.Count > 0)
                        {
                            DataTransfer SendingData = datas.Dequeue();//前面已经确保了DataTransfer不为空
                            try
                            {
                                string json = Newtonsoft.Json.JsonConvert.SerializeObject(SendingData);
                                byte[] bufs = Encoding.UTF8.GetBytes(json);
                                Sendclient.Send(bufs, bufs.Length, SendPort);
                            }
                            catch (Exception e)
                            {
                                DiscoveryLogServer[SendingData.type].ForEach(handle => handle.Log(e.ToString()));
                            }
                        }
                    }
                    else
                    {
                        //ManagerLog("空转");
                        Thread.Sleep(sendMillSec);
                    }
                }catch (Exception e)
                {
                    ManagerLog(e.ToString());
                }
            }
        }
Exemple #45
0
 // When server IP settings is changed during runtime, call this method to take the effect.
 public void Init(string serverIp, int port)
 {
     client = new UdpClient();
     server = new IPEndPoint(IPAddress.Parse(serverIp), port);
 }
Exemple #46
0
 public UdpClientAdapter(int port)
 {
     _udpClient = new UdpClient(port);
 }
 public void OpenClient(int port)
 {
     udpClient = new UdpClient(port);
 }
Exemple #48
0
    public static void Main(string[] args)
    {
        IntPtr ctx;
        IntPtr ssl;

        /* These paths should be changed according to use */
        string        fileCert = @"server-cert.pem";
        string        fileKey  = @"server-key.pem";
        StringBuilder dhparam  = new StringBuilder("dh2048.pem");

        wolfssl.psk_delegate psk_cb = new wolfssl.psk_delegate(my_psk_server_cb);

        StringBuilder buff  = new StringBuilder(1024);
        StringBuilder reply = new StringBuilder("Hello, this is the wolfSSL C# wrapper");

        wolfssl.Init();

        Console.WriteLine("Calling ctx Init from wolfSSL");
        ctx = wolfssl.CTX_dtls_new(wolfssl.useDTLSv1_2_server());
        if (ctx == IntPtr.Zero)
        {
            Console.WriteLine("Error creating ctx structure");
            return;
        }

        Console.WriteLine("Finished init of ctx .... now load in cert and key");

        if (!File.Exists(fileCert) || !File.Exists(fileKey))
        {
            Console.WriteLine("Could not find cert or key file");
            wolfssl.CTX_free(ctx);
            return;
        }


        if (wolfssl.CTX_use_certificate_file(ctx, fileCert, wolfssl.SSL_FILETYPE_PEM) != wolfssl.SUCCESS)
        {
            Console.WriteLine("Error setting cert file");
            wolfssl.CTX_free(ctx);
            return;
        }


        if (wolfssl.CTX_use_PrivateKey_file(ctx, fileKey, wolfssl.SSL_FILETYPE_PEM) != wolfssl.SUCCESS)
        {
            Console.WriteLine("Error setting key file");
            wolfssl.CTX_free(ctx);
            return;
        }


        /* Test psk use with DHE */
        StringBuilder hint = new StringBuilder("cyassl server");

        if (wolfssl.CTX_use_psk_identity_hint(ctx, hint) != wolfssl.SUCCESS)
        {
            Console.WriteLine("Error setting hint");
            wolfssl.CTX_free(ctx);
            return;
        }
        wolfssl.CTX_set_psk_server_callback(ctx, psk_cb);

        short minDhKey = 128;

        wolfssl.CTX_SetMinDhKey_Sz(ctx, minDhKey);
        Console.Write("Setting cipher suite to ");
        StringBuilder set_cipher = new StringBuilder("DHE-PSK-AES128-CBC-SHA256");

        Console.WriteLine(set_cipher);
        if (wolfssl.CTX_set_cipher_list(ctx, set_cipher) != wolfssl.SUCCESS)
        {
            Console.WriteLine("Failed to set cipher suite");
            wolfssl.CTX_free(ctx);
            return;
        }

        IPAddress  ip  = IPAddress.Parse("0.0.0.0");
        UdpClient  udp = new UdpClient(11111);
        IPEndPoint ep  = new IPEndPoint(ip, 11111);

        Console.WriteLine("Started UDP and waiting for a connection");

        ssl = wolfssl.new_ssl(ctx);
        if (ssl == IntPtr.Zero)
        {
            Console.WriteLine("Error creating ssl object");
            udp.Close();
            wolfssl.CTX_free(ctx);
            return;
        }

        if (wolfssl.SetTmpDH_file(ssl, dhparam, wolfssl.SSL_FILETYPE_PEM) != wolfssl.SUCCESS)
        {
            Console.WriteLine("Error in setting dhparam");
            Console.WriteLine(wolfssl.get_error(ssl));
            udp.Close();
            clean(ssl, ctx);
            return;
        }

        if (wolfssl.set_dtls_fd(ssl, udp, ep) != wolfssl.SUCCESS)
        {
            Console.WriteLine(wolfssl.get_error(ssl));
            udp.Close();
            clean(ssl, ctx);
            return;
        }

        if (wolfssl.accept(ssl) != wolfssl.SUCCESS)
        {
            Console.WriteLine(wolfssl.get_error(ssl));
            udp.Close();
            clean(ssl, ctx);
            return;
        }

        /* print out results of TLS/SSL accept */
        Console.WriteLine("SSL version is " + wolfssl.get_version(ssl));
        Console.WriteLine("SSL cipher suite is " + wolfssl.get_current_cipher(ssl));

        /* get connection information and print ip - port */
        wolfssl.DTLS_con con = wolfssl.get_dtls_fd(ssl);
        Console.Write("Connected to ip ");
        Console.Write(con.ep.Address.ToString());
        Console.Write(" on port ");
        Console.WriteLine(con.ep.Port.ToString());

        /* read information sent and send a reply */
        if (wolfssl.read(ssl, buff, 1023) < 0)
        {
            Console.WriteLine("Error reading message");
            Console.WriteLine(wolfssl.get_error(ssl));
            udp.Close();
            clean(ssl, ctx);
            return;
        }
        Console.WriteLine(buff);

        if (wolfssl.write(ssl, reply, reply.Length) != reply.Length)
        {
            Console.WriteLine("Error writing message");
            Console.WriteLine(wolfssl.get_error(ssl));
            udp.Close();
            clean(ssl, ctx);
            return;
        }

        Console.WriteLine("At the end freeing stuff");
        wolfssl.shutdown(ssl);
        udp.Close();
        clean(ssl, ctx);
    }
Exemple #49
0
 /// <summary>
 /// 构造函数,自动分配端口号
 /// </summary>
 public UdpSocketClient()
 {
     _udpClient = new UdpClient(0);
 }
Exemple #50
0
        /// <summary>
        ///     Handles the callback.
        /// </summary>
        /// <param name="ar">The results</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            UdpClient listener = (UdpClient)ar.AsyncState;

            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 = new IPEndPoint(0, 0);

            Byte[] receiveBytes;
            try
            {
                receiveBytes = listener.EndReceive(ar, ref senderEndpoint);
            }
            catch (Exception e)
            {
                if (listener.Client == null)
                {
                    return;
                }
                Log.Debug(e);
                try
                {
                    listener.BeginReceive(ReceiveCallback, listener);
                }
                catch (ObjectDisposedException dex)
                {
                    // Log and move on. Should probably free up the player and remove them here.
                    Log.Debug(dex);
                }

                return;
            }

            if (receiveBytes.Length != 0)
            {
                if (listener.Client == null)
                {
                    return;
                }
                listener.BeginReceive(ReceiveCallback, listener);

                if (listener.Client == null)
                {
                    return;
                }
                try
                {
                    ProcessMessage(receiveBytes, senderEndpoint);
                }
                catch (Exception e)
                {
                    Log.Error("Processing", e);
                }
            }
            else
            {
                Log.Debug("Unexpected end of transmission?");
            }
        }
Exemple #51
0
 public ReceiverUdpClientBased(IPEndPoint withLockalEP)
 {
     LockalEndPoint    = withLockalEP;
     NetClient         = new UdpClient(LockalEndPoint); //было LockalEndPoint.Port
     _recieving_cancel = _recivingCancelTokenSource.Token;
 }
Exemple #52
0
 /// <summary>
 /// 启动服务
 /// </summary>
 public void Start()
 {
     _udpClient = new UdpClient(_port);
     StartRecMsg();
     HandleStarted?.BeginInvoke(null, null);
 }
Exemple #53
0
 public Tftp(int localPort, string remoteIP, TftpMsg msg_CallBack)
 {
     this.remoteIP     = remoteIP;
     this.msg_CallBack = msg_CallBack;
     client            = new UdpClient(localPort);
 }
Exemple #54
0
 public DataServer(int port)
 {
     _fileQueue = new ConcurrentQueue <string>();
     _endPoint  = new IPEndPoint(IPAddress.Any, port);
     _listener  = new UdpClient(_endPoint);
 }
Exemple #55
0
        private async void StartSITL(string exepath, string model, string homelocation, string extraargs = "", int speedup = 1)
        {
            if (String.IsNullOrEmpty(homelocation))
            {
                CustomMessageBox.Show(Strings.Invalid_home_location, Strings.ERROR);
                return;
            }

            if (!File.Exists(exepath))
            {
                CustomMessageBox.Show(Strings.Failed_to_download_the_SITL_image, Strings.ERROR);
                return;
            }

            // kill old session
            try
            {
                if (simulator != null)
                {
                    simulator.Kill();
                }
            }
            catch
            {
            }

            // override default model
            if (cmb_model.Text != "")
            {
                model = cmb_model.Text;
            }

            var config = await GetDefaultConfig(model);

            if (!string.IsNullOrEmpty(config))
            {
                extraargs += @" --defaults """ + config + @"""";
            }

            extraargs += " " + txt_cmdline.Text + " ";

            if (chk_wipe.Checked)
            {
                extraargs += " --wipe ";
            }

            string simdir = sitldirectory + model + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(simdir);

            string path = Environment.GetEnvironmentVariable("PATH");

            Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path, EnvironmentVariableTarget.Process);

            Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

            ProcessStartInfo exestart = new ProcessStartInfo();

            exestart.FileName         = exepath;
            exestart.Arguments        = String.Format("-M{0} -O{1} -s{2} --uartA tcp:0 {3}", model, homelocation, speedup, extraargs);
            exestart.WorkingDirectory = simdir;
            exestart.WindowStyle      = ProcessWindowStyle.Minimized;
            exestart.UseShellExecute  = true;

            try
            {
                simulator = System.Diagnostics.Process.Start(exestart);
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show("Failed to start the simulator\n" + ex.ToString(), Strings.ERROR);
                return;
            }

            System.Threading.Thread.Sleep(2000);

            MainV2.View.ShowScreen(MainV2.View.screens[0].Name);

            var client = new Comms.TcpSerial();

            try
            {
                client.client = new TcpClient("127.0.0.1", 5760);

                MainV2.comPort.BaseStream = client;

                SITLSEND = new UdpClient("127.0.0.1", 5501);

                Thread.Sleep(200);

                MainV2.instance.doConnect(MainV2.comPort, "preset", "5760");
            }
            catch
            {
                CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                return;
            }
        }
Exemple #56
0
        private void SendWOL(byte[] macaddr, IPAddress ipaddr)
        {
            var packet = new List <byte>();

            for (var i = 0; i < 6; i++)
            {
                packet.Add(0xFF);
            }
            for (var i = 0; i < 16; i++)
            {
                packet.AddRange(macaddr);
            }

            WriteDebug($"Sending UDP package to [{IPAddress.Broadcast}]:{42} with data\n{EncodingConverter.ByteArrayToHexDump(packet, ":", 6, "", true)}");
            WriteDebug();

            using (var client = new UdpClient())
            {
                client.Connect(IPAddress.Broadcast, 42);
                client.Send(packet.ToArray(), packet.Count);
                client.Close();
            }

            if (ipaddr != null && ipaddr.AddressFamily == AddressFamily.InterNetwork)
            {
                WriteDebug($"Trying to determine the broadcast adress for [{ipaddr}] in all available adapters");
                WriteDebug();

                foreach (var iface in NetworkInterface.GetAllNetworkInterfaces().Where(p => p.NetworkInterfaceType != NetworkInterfaceType.Loopback).OrderBy(p => p.OperationalStatus))
                {
                    var anymatch = false;
                    foreach (var ipinfo in iface.GetIPProperties().UnicastAddresses.AsEnumerable().Where(p => p.Address.AddressFamily == AddressFamily.InterNetwork))
                    {
                        if (ipaddr.IsPartOfSubnet(ipinfo.Address, ipinfo.IPv4Mask))
                        {
                            WriteDebug($"Found matching subnet [{ipinfo.Address}|{ipinfo.IPv4Mask}] in adapter \"{iface.Name}\"");
                            WriteDebug();

                            anymatch = true;

                            var broadcast = ipinfo.Address.GetBroadcastAddress(ipinfo.IPv4Mask);
                            if (broadcast == null)
                            {
                                continue;
                            }

                            WriteDebug($"Sending UDP package to [{broadcast}]:{42} with data\n{EncodingConverter.ByteArrayToHexDump(packet, ":", 6, "", true)}");
                            WriteDebug();

                            using (var client = new UdpClient())
                            {
                                client.Connect(broadcast, 42);
                                client.Send(packet.ToArray(), packet.Count);
                                client.Close();
                            }
                        }
                    }
                    if (!anymatch)
                    {
                        WriteDebug($"Found no matching subnet in adapter \"{iface.Name}\"");
                        WriteDebug();
                    }
                }
            }
        }
Exemple #57
0
        private void CreatePortMapListen(UdpClient udpClient, Mapping mapping)
        {
            IPEndPoint endPoint = new IPEndPoint(LocalAddress, PmpConstants.ServerPort);

            while (true)
            {
                byte[] data = udpClient.Receive(ref endPoint);

                if (data.Length < 16)
                {
                    continue;
                }

                if (data[0] != PmpConstants.Version)
                {
                    continue;
                }

                byte opCode = (byte)(data[1] & 127);

                NetworkProtocolType protocol = NetworkProtocolType.Tcp;
                if (opCode == PmpConstants.OperationCodeUdp)
                {
                    protocol = NetworkProtocolType.Udp;
                }

                short resultCode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 2));
                int   epoch      = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 4));

                short privatePort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 8));
                short publicPort  = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 10));

                uint lifetime = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 12));

                if (privatePort < 0 || publicPort < 0 || resultCode != PmpConstants.ResultCodeSuccess)
                {
                    string[] errors = new[]
                    {
                        "Success",
                        "Unsupported Version",
                        "Not Authorized/Refused (e.g. box supports mapping, but user has turned feature off)"
                        ,
                        "Network Failure (e.g. NAT box itself has not obtained a DHCP lease)",
                        "Out of resources (NAT box cannot create any more mappings at this time)",
                        "Unsupported opcode"
                    };
                    throw new MappingException(resultCode, errors[resultCode]);
                }

                if (lifetime == 0)
                {
                    return;                                //mapping was deleted
                }
                //mapping was created
                //TODO: verify that the private port+protocol are a match
                mapping.PublicPort          = publicPort;
                mapping.NetworkProtocolType = protocol;
                mapping.Expiration          = DateTime.Now.AddSeconds(lifetime);
                return;
            }
        }
Exemple #58
0
        public bool writeData(UdpClient client, string filePath, byte xor)
        {
            bool     ret             = true;
            FileInfo fileInfo        = new FileInfo(filePath);
            long     fileTotalLength = fileInfo.Length;
            long     fileWriteLenght = 0;

            try
            {
                FileStream fileStreamIn = File.OpenRead(filePath);
                byte[]     buffer       = new byte[TFTP_MAX_DATE_SIZE];
                int        readLenth    = 0;
                UInt16     nextBlock    = 0;
                do
                {
                    readLenth = fileStreamIn.Read(buffer, 0, buffer.Length);
                    for (int i = 0; i < readLenth; ++i)
                    {
                        buffer[i] ^= xor;
                    }
                    nextBlock++;

                    WriteData outData;
                    outData.opCode = Utils.htons((UInt16)TftpCode.Data);
                    outData.block  = Utils.htons(nextBlock);
                    outData.data   = buffer;
                    byte[] bytes = Struct.StructToBytes(outData);

                    int  count   = 0;
                    bool replyOK = false;
                    do
                    {
                        try
                        {
                            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse(remoteIP), remotePort);
                            client.Send(bytes, Marshal.SizeOf(outData.opCode)
                                        + Marshal.SizeOf(outData.block) + readLenth, remoteIpEndPoint);

                            Reply reply;
                            do
                            {
                                IPEndPoint remoteEP     = new IPEndPoint(IPAddress.Any, 0);
                                byte[]     receiveBytes = client.Receive(ref remoteEP);
                                reply        = (Reply)Struct.BytesToStuct(receiveBytes, typeof(Reply));
                                reply.opCode = Utils.htons(reply.opCode);
                                reply.block  = Utils.htons(reply.block);
                            } while ((reply.opCode != (UInt16)TftpCode.Ack) || (reply.block != nextBlock));
                            replyOK = true;
                        }
                        catch
                        {
                            count++;
                            msg_CallBack?.Invoke(TftpStatus.Err_Retry, count.ToString());
                        }
                        finally
                        {
                            if (count >= retryCnt)
                            {
                                ret = false;
                            }
                        }
                    } while ((replyOK == false) && (ret == true));
                    /* 发送进度 */
                    if (replyOK == true)
                    {
                        fileWriteLenght += readLenth;
                        int progress = (int)((float)fileWriteLenght / fileTotalLength * 100);
                        msg_CallBack?.Invoke(TftpStatus.WriteProgress, progress.ToString());
                    }
                } while ((ret == true) && (readLenth >= TFTP_MAX_DATE_SIZE)); /* 最后的数据包长度为0时,仍要发送给服务器 */
                if (ret == true)
                {
                    msg_CallBack?.Invoke(TftpStatus.Success, "发送 [ " + fileWriteLenght.ToString() + "/" +
                                         fileTotalLength.ToString() + " ] Bytes!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(false);
            }
            return(ret);
        }
Exemple #59
0
        private void StartPing()
        {
            Logger.Info("Pinging Server - Starting");

            byte[] message = _guidAsciiBytes;

            // Force immediate ping once to avoid race condition before starting to listen
            _listener.Send(message, message.Length, _serverEndpoint);

            var thread = new Thread(() =>
            {
                //wait for initial sync - then ping
                if (_pingStop.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(2)))
                {
                    return;
                }

                _ready = true;

                while (!_stop)
                {
                    //Logger.Info("Pinging Server");
                    try
                    {
                        if (_listener != null)
                        {
                            _listener.Send(message, message.Length, _serverEndpoint);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "Exception Sending Audio Ping! " + e.Message);
                    }

                    //wait for cancel or quit
                    var cancelled = _pingStop.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(15));

                    if (cancelled)
                    {
                        return;
                    }

                    TimeSpan diff = TimeSpan.FromTicks(DateTime.Now.Ticks - _udpLastReceived);

                    //reconnect to UDP - port is no good!
                    if (diff.TotalSeconds > UDP_VOIP_TIMEOUT)
                    {
                        Logger.Error("VoIP Timeout - Recreating VoIP Connection");
                        _ready = false;
                        try
                        {
                            _listener?.Close();
                        }catch (Exception ex)
                        { }

                        _listener = null;

                        _udpLastReceived = 0;

                        _listener = new UdpClient();
                        try
                        {
                            _listener.AllowNatTraversal(true);
                        }
                        catch { }

                        try
                        {
                            // Force immediate ping once to avoid race condition before starting to listen
                            _listener.Send(message, message.Length, _serverEndpoint);
                            _ready = true;
                            Logger.Error("VoIP Timeout - Success Recreating VoIP Connection");
                        }
                        catch (Exception e) {
                            Logger.Error(e, "Exception Sending Audio Ping! " + e.Message);
                        }
                    }
                }
            });

            thread.Start();
        }
Exemple #60
0
        /// <summary>
        /// Enable detailed SIP log messages.
        /// </summary>
        private static void EnableTraceLogs(SIPTransport sipTransport)
        {
            UdpClient homerSIPClient = null;

            if (HOMER_SERVER_ADDRESS != null)
            {
                homerSIPClient = new UdpClient(0, AddressFamily.InterNetwork);
            }

            sipTransport.SIPRequestInTraceEvent += (localEP, remoteEP, req) =>
            {
                Log.LogDebug($"Request received: {localEP}<-{remoteEP}");
                Log.LogDebug(req.ToString());

                if (homerSIPClient != null)
                {
                    var hepBuffer = HepPacket.GetBytes(remoteEP, localEP, DateTime.Now, 333, "myHep", req.ToString());
                    homerSIPClient.SendAsync(hepBuffer, hepBuffer.Length, HOMER_SERVER_ADDRESS, HOMER_SERVER_PORT);
                }
            };

            sipTransport.SIPRequestOutTraceEvent += (localEP, remoteEP, req) =>
            {
                Log.LogDebug($"Request sent: {localEP}->{remoteEP}");
                Log.LogDebug(req.ToString());

                if (homerSIPClient != null)
                {
                    var hepBuffer = HepPacket.GetBytes(localEP, remoteEP, DateTime.Now, 333, "myHep", req.ToString());
                    homerSIPClient.SendAsync(hepBuffer, hepBuffer.Length, HOMER_SERVER_ADDRESS, HOMER_SERVER_PORT);
                }
            };

            sipTransport.SIPResponseInTraceEvent += (localEP, remoteEP, resp) =>
            {
                Log.LogDebug($"Response received: {localEP}<-{remoteEP}");
                Log.LogDebug(resp.ToString());

                if (homerSIPClient != null)
                {
                    var hepBuffer = HepPacket.GetBytes(remoteEP, localEP, DateTime.Now, 333, "myHep", resp.ToString());
                    homerSIPClient.SendAsync(hepBuffer, hepBuffer.Length, HOMER_SERVER_ADDRESS, HOMER_SERVER_PORT);
                }
            };

            sipTransport.SIPResponseOutTraceEvent += (localEP, remoteEP, resp) =>
            {
                Log.LogDebug($"Response sent: {localEP}->{remoteEP}");
                Log.LogDebug(resp.ToString());

                if (homerSIPClient != null)
                {
                    var hepBuffer = HepPacket.GetBytes(localEP, remoteEP, DateTime.Now, 333, "myHep", resp.ToString());
                    homerSIPClient.SendAsync(hepBuffer, hepBuffer.Length, HOMER_SERVER_ADDRESS, HOMER_SERVER_PORT);
                }
            };

            sipTransport.SIPRequestRetransmitTraceEvent += (tx, req, count) =>
            {
                Log.LogDebug($"Request retransmit {count} for request {req.StatusLine}, initial transmit {DateTime.Now.Subtract(tx.InitialTransmit).TotalSeconds.ToString("0.###")}s ago.");
            };

            sipTransport.SIPResponseRetransmitTraceEvent += (tx, resp, count) =>
            {
                Log.LogDebug($"Response retransmit {count} for response {resp.ShortDescription}, initial transmit {DateTime.Now.Subtract(tx.InitialTransmit).TotalSeconds.ToString("0.###")}s ago.");
            };
        }