示例#1
3
    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();
    }
示例#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);
          }
    }
    IEnumerator StartBroadcast()
    {
        // multicast send setup
        udp_client = new UdpClient ();
        udp_client.JoinMulticastGroup (group_address);
        IPEndPoint remote_end = new IPEndPoint (group_address, startup_port);

        // sends multicast
        while (true)
        {
            byte[] buffer = Encoding.ASCII.GetBytes ("GameServer");
            udp_client.Send (buffer, buffer.Length, remote_end);

            yield return new WaitForSeconds (1);
        }
    }
    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);
    }
示例#5
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();
   }
示例#6
0
 private void Send()
 {
     while (_send)
     {
         var bytes     = _ka52.GetBytes();
         var bytesSvvo = GetByte();
         _sendClient?.Send(bytes, bytes.Length, "127.0.0.1", 20020);
         _sendClient?.Send(bytesSvvo, bytesSvvo.Length, "127.0.0.1", 6100);
         Thread.Sleep(20);
     }
 }
示例#7
0
        private void OnMediaOpened(object sender, EventArgs e)
        {
            var send = "duration:";

            if (sender is MediaElement player1)
            {
                send += player1.NaturalDuration.TimeSpan.TotalSeconds;
            }
            else if (sender is Unosquare.FFME.MediaElement player2)
            {
                send += player2.NaturalDuration?.TotalSeconds;
                //Debug.WriteLine("video size:{0},{1}", player2.NaturalVideoWidth, player2.NaturalVideoHeight);
            }
            udpClient?.Send(send, IPAddress.Broadcast.ToString(), 10241);
        }
    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 ();
    }
示例#9
0
 private void UdpSendData(byte[] datas, int length)
 {
     if (_currentEndPoint != null)
     {
         _udpClient?.Send(datas, length, _currentEndPoint);
     }
 }
示例#10
0
 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);
     }
 }
示例#11
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();
        }
    }
示例#12
0
        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();
        }
示例#13
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;
            }
        }
    }
示例#14
0
 public void Send()
 {
     UdpClient client = new UdpClient();
     IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 15000);
     byte[] bytes = Encoding.ASCII.GetBytes("Foo");
     client.Send(bytes, bytes.Length, ip);
     client.Close();
 }
示例#15
0
 private void QueueUdpPacket(object data)
 {
     udpService?.Accept(() =>
     {
         byte[] packet = Encoding.Default.GetBytes(data.ToJson());
         sensuClientSocket?.Send(packet, packet.Length);
     });
 }
示例#16
0
 public void broadCastCloudRequests(bool continuous)
 {
     UdpClient udp = new UdpClient ();
     string message = CloudMessage.createRequestMessage (continuous ? 1 : 0);
     byte[] data = Encoding.UTF8.GetBytes (message);
     IPEndPoint remoteEndPoint = new IPEndPoint (IPAddress.Broadcast, TrackerProperties.Instance.listenPort + 1);
     udp.Send (data, data.Length, remoteEndPoint);
 }
示例#17
0
	void broadcast(string message) {
		// multicast send setup
		udp_client = new UdpClient ();
		udp_client.JoinMulticastGroup (group_address);
		remote_end = new IPEndPoint (group_address, port);

		byte[] buffer = Encoding.ASCII.GetBytes (message);
		udp_client.Send (buffer, buffer.Length, remote_end);
	}
示例#18
0
 protected void sendMessage(string message)
 {
     if (String.IsNullOrWhiteSpace(message))
     {
         throw (new Exception(BasicErrorMessage.InvalidSendString));
     }
     byte[] data = Encoding.UTF8.GetBytes(message);
     client?.Send(data, data.Length, remoteEndPoint);
 }
示例#19
0
文件: test.cs 项目: mono/gert
	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);
		}
	}
示例#20
0
 static void Main(string[] args)
 {
     UdpClient client = new UdpClient("127.0.0.1", 0);
     client.Receive += (o, e) => {
         Console.WriteLine(Encoding.UTF8.GetString(
             e.Data, 0, e.Count));
     };
     client.Send("http://www.163.com", "127.0.0.1", 8089);
     Console.Read();
 }
示例#21
0
	public static void Main ()
	{
		var ip = IPAddress.Parse ("239.255.255.250");
		var bytes = new byte [] {60, 70, 75};
		UdpClient udp = new UdpClient ();
		udp.Connect (ip, 3802);
		udp.Send (bytes, 3);
		Console.WriteLine ("Sent");
		udp.Close ();
	}
示例#22
0
 public void Send(string msg)
 {
     if (udpClient != null)
     {
         IPAddress  remoteIpAddr = IPAddress.Parse(remoteIp);
         IPEndPoint remotePoint  = new IPEndPoint(remoteIpAddr, remotePort);
         byte[]     buffer       = Encoding.UTF8.GetBytes(msg);
         udpClient?.Send(buffer, buffer.Length, remotePoint);
     }
 }
示例#23
0
 private void Broadcast()
 {
     if (IsBroadcasting()) {
         UdpClient client = new UdpClient();
         IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, port);
         byte[] data = Encoding.ASCII.GetBytes(message);
         client.Send(data, data.Length, ip);
         client.Close();
     }
 }
示例#24
0
    public void Init(string nothing)
    {
        remoteEndPoint = new IPEndPoint(IPAddress.Parse(remoteAddress), remotePort);
        timestamps = new Dictionary<string, Timestamp>();
        receivedMsgBuffer = new StringBuilder();
        completeMsgBuffer = new List<string>();

        try
        {
            TCPBuffer = new byte[1024];

            sendingUDPClient = new UdpClient();
            sendingUDPClient.ExclusiveAddressUse = false;
            sendingUDPClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            sendingUDPClient.Connect(remoteAddress, remotePort);

            receivingUDPClient = new UdpClient();
            receivingUDPClient.ExclusiveAddressUse = false;
            receivingUDPClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            receivingUDPClient.Client.Bind((IPEndPoint)sendingUDPClient.Client.LocalEndPoint);
            receivingUDPClient.Connect(remoteAddress, remotePort);
            receivingUDPClient.BeginReceive(new AsyncCallback(OnMessageUDP), null);

            // Send initial message to register the address and port at the server
            string hello = "Hello Server";
            byte[] bytes = Encoding.UTF8.GetBytes(hello);

            try
            {
                sendingUDPClient.Send(bytes, bytes.Length);
            }
            catch (Exception err)
            {
        #if !UNITY_EDITOR
                    Application.ExternalCall(onErrorCallback, "An error occurred while sending the initial message to the server: " + err.Message);
        #else
                    UnityEngine.Debug.LogError("An error occurred while sending the initial message to the server: " + err.Message);
        #endif
            }

            TCPClient = new TcpClient();
            TCPClient.NoDelay = true;
            TCPClient.Connect(remoteEndPoint);
            TCPClient.GetStream().BeginRead(TCPBuffer, 0, 1024, new AsyncCallback(OnMessageTCP), null);
        }
        catch (Exception err)
        {
        #if !UNITY_EDITOR
                Application.ExternalCall(onErrorCallback, err.ToString());
        #else
                UnityEngine.Debug.LogError("Init(): " + err.ToString());
        #endif
        }
    }
示例#25
0
 void Sender()
 {
     using (UdpClient client = new UdpClient(ipAddress, port)){
         while (isSending)
         {
             buffer = Encoding.ASCII.GetBytes(data);
             client.Send(buffer, buffer.Length);
             Thread.Sleep((int)(1.0f / frequence * 1000));
         }
     }
 }
示例#26
0
 public void Send(byte[] dgram, string hostname, int port)
 {
     try
     {
         _sendClient?.Send(dgram, dgram.Length, hostname, port);
     }
     catch (Exception expSend)
     {
         Console.WriteLine(expSend.ToString());
     }
 }
示例#27
0
 private void SendPacket(int length)
 {
     try
     {
         _udpClient?.Send(_dummyData, length, "255.255.255.255", Port);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex);
     }
 }
示例#28
0
        internal override bool SendFrame(KnxFrame frame)
        {
            var byteFrame = frame.ToFrame();

            KnxHelper.Logger.LogTrace($"Writing {frame}");
            KnxHelper.Logger.LogHexOut(byteFrame);

            var length = _client?.Send(byteFrame, byteFrame.Length);

            return(length == byteFrame.Length);
        }
示例#29
0
 public void Send(byte[] dgram, string hostname, int port)
 {
     try
     {
         _sendClient?.Send(dgram, dgram.Length, hostname, port);
     }
     catch (Exception expSend)
     {
         MessageBox.Show(expSend.ToString());
     }
 }
示例#30
0
        /// <summary>
        ///     Send a byte array value as data to specified address
        /// </summary>
        /// <param name="address">KNX Address</param>
        /// <param name="data">Byte array value</param>
        public async void Action(string address, string type, object value)
        {
            byte[] asdu      = DataPointTranslator.Instance.ToASDU(type, value);
            var    cemi      = KnxCEMI.CreateActionCEMI(_messageCode, address, asdu);
            var    cemiBytes = cemi.ToBytes();

            // header
            var header = new byte[10];

            header[00] = 0x06; /* 06 - Header Length */
            header[01] = 0x10; /* 10 - KNXnet version (1.0) */
            header[02] = 0x04; /* 04 - hi-byte Service type descriptor (TUNNELLING_REQUEST) */
            header[03] = 0x20; /* 20 - lo-byte Service type descriptor (TUNNELLING_REQUEST) */
            var totalLength = BitConverter.GetBytes(header.Length + cemiBytes.Length);

            header[04] = totalLength[1];
            header[05] = totalLength[0];

            /* Connection Header (4 Bytes) */
            header[06] = 0x04; /* 04 - Structure length */
            header[07] = _channelId;
            header[08] = _sequenceNo++;
            header[09] = 0x00; /* 00 - Reserved */

            var datagram = new byte[header.Length + cemiBytes.Length];

            Array.Copy(header, datagram, header.Length);
            Array.Copy(cemiBytes, 0, datagram, header.Length, cemiBytes.Length);

            await _udpClient?.Send(datagram);
        }
        private void StartPing()
        {
            Logger.Debug($"{_mainClient.LogClientId}| Pinging Server - Starting");

            var 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;
                }

                while (!_stop)
                {
                    //Logger.Info("Pinging Server");
                    try
                    {
                        if (!RadioSendingState.IsSending)
                        {
                            Logger.Trace($"{_mainClient.LogClientId}| Sending UDP Ping to server {_serverEndpoint}: {_guid}");
                            _listener?.Send(message, message.Length, _serverEndpoint);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, $"{_mainClient.LogClientId}| Exception Sending UDP Ping! " + e.Message);
                    }

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

                    if (cancelled)
                    {
                        Logger.Debug($"{_mainClient.LogClientId}| Stopping UDP Server Ping to {_serverEndpoint} due to cancellation");
                        return;
                    }
                }

                Logger.Debug($"{_mainClient.LogClientId}| Stopping UDP Server Ping to {_serverEndpoint} due to leaving thread");
            })
            {
                Name = $"{_mainClient.LogClientId}| UDP Ping Sender"
            };

            thread.Start();
        }
示例#32
0
    IEnumerator SendCandidate()
    {
        // multicast send setup
        UdpClient udp_client = new UdpClient ();
        udp_client.JoinMulticastGroup (group_address);
        IPEndPoint remote_end = new IPEndPoint (group_address, startup_port);

        // sends multicast
        while (true)
        {
            byte[] buffer = Encoding.ASCII.GetBytes (SystemInfo.deviceUniqueIdentifier);
            udp_client.Send (buffer, buffer.Length, remote_end);
            yield return new WaitForSeconds (1);
        }
    }
示例#33
0
        public static void Send(string message)
        {
            var messageInByte = Encoding.ASCII.GetBytes(message);

            try
            {
                _client?.Send(messageInByte, messageInByte.Length);
            }
            catch (Exception e)
            {
                IsConnected = false;
                Log.Debug("Sending error: ", e.Message);
                throw;
            }
        }
示例#34
0
        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();
        }
示例#35
0
文件: test.cs 项目: mono/gert
	static int Main (string [] args)
	{
		int port = 8001;
		UdpClient udpClient = new UdpClient (port);
		IPAddress ip = IPAddress.Parse ("224.0.0.2");
		udpClient.JoinMulticastGroup (ip, IPAddress.Any);
		udpClient.MulticastLoopback = true;
		udpClient.Ttl = 1;
		udpClient.BeginReceive (ReceiveNotification, udpClient);
		udpClient.Send (new byte [1] { 255 }, 1, new IPEndPoint (ip, port));
		System.Threading.Thread.Sleep (1000);
		udpClient.DropMulticastGroup (ip);
		if (!_receivedNotification)
			return 1;
		return 0;
	}
示例#36
0
        public void StartPing()
        {
            Logger.Debug($"{_mainClient.LogClientId}| Pinging Server - Starting");

            var message = _guidAsciiBytes;

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

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

            //wait for initial sync - then ping
            if (_pingStop.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(2)))
            {
                return;
            }

            while (!_requestStop)
            {
                //Logger.Info("Pinging Server");
                try
                {
                    if (!RadioSendingState.IsSending)
                    {
                        Logger.Trace($"{_mainClient.LogClientId}| Sending UDP Ping to server {_serverEndpoint}: {_guid}");
                        _listener?.Send(message, message.Length, _serverEndpoint);
                    }
                }
                catch (Exception e)
                {
                    Logger.Error(e, $"{_mainClient.LogClientId}| Exception Sending UDP Ping! " + e.Message);
                }

                if (_pingStop.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(15)))
                {
                    return;
                }
            }

            Logger.Debug($"{_mainClient.LogClientId}| Stopping PingLoop because RequestStop is {_requestStop}");
        }
    internal void SendUDPMessage()
    {
        //if ( messages.Count > 0 )
        if ( String.IsNullOrEmpty ( message ) == false )
        {

            IPHostEntry host = Dns.GetHostEntry ( Dns.GetHostName ());;
            string localIP = null;
            //int port = 35143;

            foreach ( IPAddress ip in host.AddressList )
            {

                if ( ip.AddressFamily == AddressFamily.InterNetwork )
                {

                    localIP = ip.ToString ();
                    break;
                }
            }

            if ( startupManager.developmentMode == true )
            {

                //UnityEngine.Debug.Log ( "There are [" + messages.Count + "] messages in the queue." );
                UnityEngine.Debug.Log ( "'" + message + "' will be sent on " + localIP + " via " + port + "." );
            }

            UdpClient udpClient = new UdpClient( localIP, port );
            Byte[] sendBytes = Encoding.Unicode.GetBytes ( "[2CatStudios:UMP]" + message /*messages[0]*/ );
            try
            {

          		udpClient.Send ( sendBytes, sendBytes.Length );
                //messages.RemoveAt ( 0 );
            } catch ( Exception e )
            {

                UnityEngine.Debug.Log ( e.ToString ());
            }
        }
    }
示例#38
0
        internal override bool SendFrame(KnxFrame frame)
        {
            var byteFrame = frame.ToFrame();

            KnxHelper.Logger.LogTrace($"Writing {frame}");
            KnxHelper.Logger.LogHexOut(byteFrame);

            try
            {
                var length = _client?.Send(byteFrame, byteFrame.Length);

                return(length == byteFrame.Length);
            }
            catch (Exception e)
            {
                KnxHelper.Logger.LogError(e, "Error writing value...");
            }

            return(false);
        }
示例#39
0
    public void run()
    {
        Debug.Log("DISCOVERY THREAD: started...");
        try {
            udpClient = new UdpClient(8888);
            //udpClient.EnableBroadcast = true; //only 4 send

            while (_isRunning)
            {
                Debug.Log(GetType().Name + ">>>Ready to receive broadcast packets!");

                // Receive a packet
                //IPEndPoint object will allow us to read datagrams sent from any source.
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 8888);

                // Blocks until a message returns on this socket from a remote host.
                Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); //updates RemoteIpEndPoint to be the sender
                string returnData = Encoding.ASCII.GetString(receiveBytes);

                // Uses the IPEndPoint object to determine which of these two hosts responded.
                Debug.Log("This is the message you received " +
                                  returnData.ToString());
                Debug.Log("This message was sent from " +
                                  RemoteIpEndPoint.Address.ToString() +
                                  " on their port number " +
                                  RemoteIpEndPoint.Port.ToString());

                // See if the packet holds the right command (message)
                string message = returnData.ToString().Trim();
                if (message.Equals("DISCOVER_FUIFSERVER_REQUEST")) {
                    Byte[] sendBytes = Encoding.ASCII.GetBytes("DISCOVER_FUIFSERVER_RESPONSE");
                    udpClient.Send(sendBytes, sendBytes.Length, RemoteIpEndPoint);
                }

            }
        } catch (Exception e) {
            Debug.LogError(e.ToString());
        }
        Debug.Log("DISCOVERY THREAD: ending...");
    }
示例#40
0
        public bool Send(byte[] bytes, int len, double[] freq, byte[] modulation)
        {
            if (!_stop &&
                _listener != null &&
                (bytes != null))
            //can only send if IL2 is connected
            {
                try
                {
                    //generate packet
                    var udpVoicePacket = new UDPVoicePacket
                    {
                        GuidBytes               = _guidAsciiBytes,
                        AudioPart1Bytes         = bytes,
                        AudioPart1Length        = (ushort)bytes.Length,
                        Frequencies             = freq,
                        UnitId                  = gameState.unitId,
                        Modulations             = modulation,
                        PacketNumber            = _packetNumber++,
                        OriginalClientGuidBytes = _guidAsciiBytes,
                        RetransmissionCount     = 0,
                        Encryptions             = new byte[] { 0 },
                    };

                    var encodedUdpVoicePacket = udpVoicePacket.EncodePacket();

                    _listener?.Send(encodedUdpVoicePacket, encodedUdpVoicePacket.Length, new IPEndPoint(_address, _port));
                }
                catch (Exception e)
                {
                    Logger.Error(e, "Exception Sending Audio Message " + e.Message);
                }
            }
            else
            {
                //couldnt send
            }

            return(false);
        }
示例#41
0
        private void PpmCollection(PpmPoint[] ppmPoints)
        {
            _routeToIup.CountPoints = 0;

            for (int i = 0; i < ppmPoints.Length; i++)
            {
                if (ppmPoints[i] == null)
                {
                    continue;
                }
                _routeToIup.CountPoints++;
                _routeToIup.NavigationPoints[i] = ppmPoints[i].NavigationPoint;
            }
            int s  = Marshal.SizeOf(_routeToIup);
            int s1 = Marshal.SizeOf(_routeToIup.ArrivalAerodrome);
            int s2 = Marshal.SizeOf(_routeToIup.NavigationPoints[0]);


            var dgram = GetByteNp();

            _sendClient?.Send(dgram, dgram.Length, "127.0.0.1", 20555);
        }
示例#42
0
    private static void Main()
    {
        string IP = "127.0.0.1";
        int port = 65002;

        IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);

        UdpClient client = new UdpClient();

        int r = 0;
        while (!Console.KeyAvailable)
        {

            byte[] data = Encoding.UTF8.GetBytes("01234567*404=" + r.ToString());
            client.Send(data, data.Length, remoteEndPoint);
            Console.Write(r.ToString());
            Thread.Sleep(2000);
            r++;
            if (r == 2)
                r = 0;
        }
        client.Close();
    }
示例#43
0
 public void Write(byte[] dados)
 {
     try
     {
         if (UdpClient?.Client == null)
         {
             return;
         }
         if (!Connected)
         {
             return;
         }
         if (!UdpClient.Client.Connected)
         {
             return;
         }
         UdpClient?.Send(dados, dados.Length);
     }
     catch (Exception erro)
     {
         throw new Exception(erro.Message);
     }
 }
示例#44
0
    // Update is called once per frame
    IEnumerator MyCoroutine()
    {
        client = new UdpClient(port);                // this is the call to port... needs to be right...
        while (true)
        {
            try
            {
                //byte[] data = Encoding.UTF8.GetBytes(message);
                byte[] data = Encoding.UTF8.GetBytes(Robot.instance.driveL.ToString() + "," + Robot.instance.driveR.ToString()
                    + ",L::" + Robot.instance.driveL.ToString() + "  R::" + Robot.instance.driveR.ToString());
                client.Send(data, data.Length, remoteEndPoint);
            }
            catch (Exception err)
            {
                print(err.ToString());
                ErrorControl.text = err.ToString();
            }
            Status.text = "Connected to: /n" + IncomingIP;

            //yield return new WaitForSeconds(0.003f);
            yield return null;
        }
    }
示例#45
0
    // -------------------------------------------------------------------------
    public void SendData(string ipString, int port, byte[] data)
    {
        UdpClient client = null;

        try
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipString), port);
            client = new UdpClient(endPoint);

            client.Send(data, data.Length, endPoint);
        }
        catch (System.Exception err)
        {
            print(err.ToString());
        }
        finally
        {
            if (client != null) {
                client.Close();
            }

        }
    }
示例#46
0
 static void SendData(string datagramm)
 {
     UdpClient uClient = new UdpClient();
     //подключение к удаленному хосту
     IPEndPoint ipEnd = new IPEndPoint(RemoteIPAddr, RemotePort);
     try
     {
         byte[] bytes = Encoding.Unicode.GetBytes(datagramm);
         uClient.Send(bytes, bytes.Length, ipEnd);
     }
     catch (SocketException sockEx)
     {
         Console.WriteLine("Ошибка сокета: " + sockEx.Message);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Ошибка : " + ex.Message);
     }
     finally
     {
         //закрытие экземпляра класса UdpClient
         uClient.Close();
     }
 }
示例#47
0
 public void Send(string ipAddress, byte[] data, int portNumber)
 {
     client?.Send(data, data.Length, new IPEndPoint(IPAddress.Parse(ipAddress), portNumber));
 }
示例#48
0
 void HeartBeat()
 {
     Byte[] sendBytes = Encoding.ASCII.GetBytes("heartbeat");
     udp.Send(sendBytes, sendBytes.Length);
 }
示例#49
0
        private void SendNext()
        {
            var nextMessage = Console.ReadLine();

            multicastClient.Send(Encoding.ASCII.GetBytes(nextMessage), nextMessage.Length, multicastEndpoint);
        }
    bool SendCommand(ref UdpClient client, string ipadr, int port)
    {
        string sendstr = sendCommand + System.Environment.NewLine;
        byte[] data = ASCIIEncoding.ASCII.GetBytes (sendstr);

        try {
            client.Send (data, data.Length, ipadr, port);
        }
        catch (Exception e) {
            rcvText.text = "snd:" + e.Message;
            return false;
        }
        return true;
    }
示例#51
0
        public AnnounceInfo Announce(String url, String hash, String peerId, Int64 bytesDownloaded, Int64 bytesLeft, Int64 bytesUploaded,
                                     Int32 eventTypeFilter, Int32 ipAddress, Int32 numWant, Int32 listenPort, Int32 extensions)
        {
            List <IPEndPoint> returnValue = new List <IPEndPoint>();

            ValidateInput(url, new[] { hash }, ScraperType.UDP);

            _currentConnectionId = BaseCurrentConnectionId;
            Int32 trasactionId = Random.Next(0, 65535);

            UdpClient udpClient = new UdpClient(Tracker, Port)
            {
                DontFragment = true,
                Client       =
                {
                    SendTimeout    = Timeout * 1000,
                    ReceiveTimeout = Timeout * 1000
                }
            };

            byte[] sendBuf = _currentConnectionId.Concat(Pack.Int32(0, Pack.Endianness.Big)).Concat(Pack.Int32(trasactionId, Pack.Endianness.Big)).ToArray();
            udpClient.Send(sendBuf, sendBuf.Length);

            IPEndPoint endPoint = null;

            byte[] recBuf;

            try
            {
                recBuf = udpClient.Receive(ref endPoint);
            }
            catch (Exception)
            {
                return(null);
            }

            if (recBuf == null)
            {
                throw new NoNullAllowedException("udpClient failed to receive");
            }
            if (recBuf.Length < 0)
            {
                throw new InvalidOperationException("udpClient received no response");
            }
            if (recBuf.Length < 16)
            {
                throw new InvalidOperationException("udpClient did not receive entire response");
            }

            UInt32 recAction       = Unpack.UInt32(recBuf, 0, Unpack.Endianness.Big);
            UInt32 recTrasactionId = Unpack.UInt32(recBuf, 4, Unpack.Endianness.Big);

            if (recAction != 0 || recTrasactionId != trasactionId)
            {
                throw new Exception("Invalid response from tracker");
            }

            _currentConnectionId = CopyBytes(recBuf, 8, 8);

            byte[] hashBytes = Pack.Hex(hash).ToArray();

            Int32 key = Random.Next(0, 65535);

            sendBuf = _currentConnectionId.                                          /*connection id*/
                      Concat(Pack.Int32(1)).                                         /*action*/
                      Concat(Pack.Int32(trasactionId, Pack.Endianness.Big)).         /*trasaction Id*/
                      Concat(hashBytes).                                             /*hash*/
                      Concat(Encoding.ASCII.GetBytes(peerId)).                       /*my peer id*/
                      Concat(Pack.Int64(bytesDownloaded, Pack.Endianness.Big)).      /*bytes downloaded*/
                      Concat(Pack.Int64(bytesLeft, Pack.Endianness.Big)).            /*bytes left*/
                      Concat(Pack.Int64(bytesUploaded, Pack.Endianness.Big)).        /*bytes uploaded*/
                      Concat(Pack.Int32(eventTypeFilter, Pack.Endianness.Big)).      /*event, 0 for none, 2 for just started*/
                      Concat(Pack.Int32(ipAddress, Pack.Endianness.Big)).            /*ip, 0 for this one*/
                      Concat(Pack.Int32(key, Pack.Endianness.Big)).                  /*unique key*/
                      Concat(Pack.Int32(numWant, Pack.Endianness.Big)).              /*num want, -1 for as many as pos*/
                      Concat(Pack.Int32(listenPort, Pack.Endianness.Big)).           /*listen port*/
                      Concat(Pack.Int32(extensions, Pack.Endianness.Big)).ToArray(); /*extensions*/
            udpClient.Send(sendBuf, sendBuf.Length);

            try
            {
                recBuf = udpClient.Receive(ref endPoint);
            }
            catch (Exception)
            {
                return(null);
            }

            recAction       = Unpack.UInt32(recBuf, 0, Unpack.Endianness.Big);
            recTrasactionId = Unpack.UInt32(recBuf, 4, Unpack.Endianness.Big);

            int waitTime = (int)Unpack.UInt32(recBuf, 8, Unpack.Endianness.Big);
            int leachers = (int)Unpack.UInt32(recBuf, 12, Unpack.Endianness.Big);
            int seeders  = (int)Unpack.UInt32(recBuf, 16, Unpack.Endianness.Big);

            if (recAction != 1 || recTrasactionId != trasactionId)
            {
                throw new Exception("Invalid response from tracker");
            }

            for (Int32 i = 20; i < recBuf.Length; i += 6)
            {
                UInt32 ip   = Unpack.UInt32(recBuf, i, Unpack.Endianness.Big);
                UInt16 port = Unpack.UInt16(recBuf, i + 4, Unpack.Endianness.Big);

                returnValue.Add(new IPEndPoint(ip, port));
            }

            udpClient.Close();

            return(new AnnounceInfo(returnValue, waitTime, seeders, leachers));
        }
    //    IEnumerator sendByteTimed(){
    void sendByteTimed()
    {
        int size_max_packet = 1024; // Taille max des paquets

        int taille_tab_final=byteImgS.Length;
        gameObject.SendMessage("tailleTemps",taille_tab_final);

        while (readCount<taille_tab_final-1) {

                //yield return new WaitForEndOfFrame();
            client = new UdpClient();
            //yield return new WaitForSeconds (0.12f);
        int length = Mathf.Min(size_max_packet, taille_tab_final-readCount);//les dernier bit <= size_max_packet ??
        int ii=0;

        byte[] DatagramPacket = new byte[length];
        float[]	DatagramPacketfloat = new float[length];
        for (int ik=readCount;ik<(readCount+length);ik++){
                //DatagramPacketfloat[ii]=(byteImgS[ik]);

                //DatagramPacket[ii]=byte.Parse((""+(byteImgS[ik])).ToString());

                float az1=(byteImgS[ik]);
                //DatagramPacket[ii]=(byte)(Mathf.Ceil(az1));
                DatagramPacket[ii]=(byte)(az1);

                //	if(ii==2)Debug.Log(DatagramPacket[ii]+"/"+az1);
                ii++; }

            //DatagramPacket = MessageDataSound.ToByteArray(DatagramPacketfloat);
            //	Debug.Log(DatagramPacket[2]+DatagramPacket[3]);
                 try
          		 	{
                        Debug.Log("DatagramPacket:"+DatagramPacket[10]+DatagramPacket[11]+DatagramPacket[12]);//+"/RD:"+readCount+"/len:"+length);

              		 client.Send(DatagramPacket,length, remoteEndPoint);
              		 client.Close();
                        readCount += length;

                    }  catch (Exception err) { Debug.Log(err.ToString()); }

        }
    }
示例#53
0
        public IDictionary <String, ScrapeInfo> Scrape(String url, String[] hashes)
        {
            Dictionary <String, ScrapeInfo> returnVal = new Dictionary <string, ScrapeInfo>();

            ValidateInput(url, hashes, ScraperType.UDP);

            Int32 trasactionId = Random.Next(0, 65535);

            UdpClient udpClient = new UdpClient(Tracker, Port)
            {
                Client =
                {
                    SendTimeout    = Timeout * 1000,
                    ReceiveTimeout = Timeout * 1000
                }
            };

            byte[] sendBuf = _currentConnectionId.Concat(Pack.Int32(0)).Concat(Pack.Int32(trasactionId)).ToArray();
            udpClient.Send(sendBuf, sendBuf.Length);

            IPEndPoint endPoint = null;

            byte[] recBuf = udpClient.Receive(ref endPoint);

            if (recBuf == null)
            {
                throw new NoNullAllowedException("udpClient failed to receive");
            }
            if (recBuf.Length < 0)
            {
                throw new InvalidOperationException("udpClient received no response");
            }
            if (recBuf.Length < 16)
            {
                throw new InvalidOperationException("udpClient did not receive entire response");
            }

            UInt32 recAction       = Unpack.UInt32(recBuf, 0, Unpack.Endianness.Big);
            UInt32 recTrasactionId = Unpack.UInt32(recBuf, 4, Unpack.Endianness.Big);

            if (recAction != 0 || recTrasactionId != trasactionId)
            {
                throw new Exception("Invalid response from tracker");
            }

            _currentConnectionId = CopyBytes(recBuf, 8, 8);

            byte[] hashBytes = new byte[0];
            hashBytes = hashes.Aggregate(hashBytes, (current, hash) => current.Concat(Pack.Hex(hash)).ToArray());

            int expectedLength = 8 + (12 * hashes.Length);

            sendBuf = _currentConnectionId.Concat(Pack.Int32(2)).Concat(Pack.Int32(trasactionId)).Concat(hashBytes).ToArray();
            udpClient.Send(sendBuf, sendBuf.Length);

            recBuf = udpClient.Receive(ref endPoint);

            if (recBuf == null)
            {
                throw new NoNullAllowedException("udpClient failed to receive");
            }
            if (recBuf.Length < 0)
            {
                throw new InvalidOperationException("udpClient received no response");
            }
            if (recBuf.Length < expectedLength)
            {
                throw new InvalidOperationException("udpClient did not receive entire response");
            }

            recAction       = Unpack.UInt32(recBuf, 0, Unpack.Endianness.Big);
            recTrasactionId = Unpack.UInt32(recBuf, 4, Unpack.Endianness.Big);

            _currentConnectionId = CopyBytes(recBuf, 8, 8);

            if (recAction != 2 || recTrasactionId != trasactionId)
            {
                throw new Exception("Invalid response from tracker");
            }

            Int32 startIndex = 8;

            foreach (String hash in hashes)
            {
                UInt32 seeders   = Unpack.UInt32(recBuf, startIndex, Unpack.Endianness.Big);
                UInt32 completed = Unpack.UInt32(recBuf, startIndex + 4, Unpack.Endianness.Big);
                UInt32 leachers  = Unpack.UInt32(recBuf, startIndex + 8, Unpack.Endianness.Big);

                returnVal.Add(hash, new ScrapeInfo(seeders, completed, leachers, ScraperType.UDP));

                startIndex += 12;
            }

            udpClient.Close();

            return(returnVal);
        }
示例#54
0
        private void buttonCreateAccount_Click(object sender, EventArgs e)
        {
            //  *************



            UdpClient  klienti = new UdpClient();
            IPEndPoint ep      = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12000);

            klienti.Connect(ep);

            byte[] bytesend = Encoding.ASCII.GetBytes
                              (
                textBoxFirstName.Text + " " +
                textBoxLastName.Text + " " +
                textBoxEmail.Text + " " +
                textBoxUsername.Text + " " +
                textBoxPassword.Text + " " +
                textBoxPasswordConfirm.Text
                              );

            klienti.Send(bytesend, bytesend.Length);


            //
            X509Certificate2 cert = GetCertificateFromStore("CN=RootCA");

            if (cert == null)
            {
                Console.WriteLine("Certificate 'CN=CERT_SIGN_TEST_CERT' not found.");
                Console.ReadLine();
            }



            string email    = textBoxUsername.Text.Trim();
            string password = textBoxPassword.Text.Trim();


            DES des = new DES();

            string mesazhi = email + ":" + password + ":" + "blla";

            Console.WriteLine(mesazhi);
            byte[] encrytedData = des.Enkripto(mesazhi);

            byte[] IV  = des.getIV();
            byte[] key = des.getKey();

            byte[] encryptedKey = EncryptDataOaepSha1(cert, key);

            Console.WriteLine(encryptedKey.Length);
            Console.WriteLine(Convert.ToBase64String(encryptedKey));

            Console.WriteLine(Convert.ToBase64String(key));
            Console.WriteLine(Convert.ToBase64String(DecryptDataOaepSha1(cert, encryptedKey)));


            string delimiter            = ".";
            string fullmessageEncrypted = Convert.ToBase64String(IV) + delimiter + Convert.ToBase64String(encryptedKey) + delimiter + Convert.ToBase64String(encrytedData);

            //
        }
示例#55
0
    public void Send(string msg)
    {
        var sendBytes = Encoding.UTF8.GetBytes(msg);

        _udpClient?.Send(sendBytes, sendBytes.Length);
    }
    /*void IPMine(){
    var hostname :String= Dns.GetHostName();
    var ips:IPAddress[] = Dns.GetHostAddresses(hostname);
    if (ips.Length > 0)MessageHostName=("SrvIP"+"/"+GameName+"/"+(ips[0].ToString()));
    sendString(MessageHostName);
    NetScripts.textWMessage+="\n....server UDP send DatagramPacket.. message"+MessageHostName+".";
    }*/
    /*
    void sendString()
       {
        gameObject.SendMessage("tailleTemps",byteImgS.Length);
           try
           {
                byte[] DatagramPacket = (byteImgS);
               //byte[] DatagramPacket = Encoding.UTF8.GetBytes(message);
               //var DatagramPacket:byte[] = Encoding.ASCII.GetBytes(message);
               client.Send(DatagramPacket, DatagramPacket.Length, remoteEndPoint);
               client.Close();

           }
           catch (Exception err) { Debug.Log(err.ToString()); }
       }

        */
    IEnumerator sendByteTimed()
    {
        int size_max_packet = 1024; // Taille max des paquets

        int taille_tab_final=byteImgS.Length;
        gameObject.SendMessage("tailleTemps",taille_tab_final);

        while (readCount<taille_tab_final-1) {

                yield return new WaitForEndOfFrame();
            client = new UdpClient();
            //yield return new WaitForSeconds (0.12f);
        //Debug.Log("readCount:"+readCount);

        int length = Mathf.Min(size_max_packet, taille_tab_final-readCount);//les dernier bit <= size_max_packet ??
        int ii=0;
        //DatagramPacket=null;
        byte[] DatagramPacket = new byte[length];
        for (int ik=readCount;ik<(readCount+length);ik++){ DatagramPacket[ii]=byteImgS[ik]; if(ii==12)Debug.Log(DatagramPacket[ii]+"/"+byteImgS[ik]); ii++; }

                 try
          		 	{
                        Debug.Log("DatagramPacket:"+DatagramPacket[10]+DatagramPacket[11]+DatagramPacket[12]);//+"/RD:"+readCount+"/len:"+length);

              		 client.Send(DatagramPacket,length, remoteEndPoint);
              		 client.Close();
                    //clientAvailableTime=0.1f;
                    //countclientAvailableTime=true;
                        readCount += length;

                    }  catch (Exception err) { Debug.Log(err.ToString()); }

        }//	else countclientAvailableTime=false;

        //if(clientAvailableTime<0){}else {Debug.Log("waiiiiiiiiiiiiiit");}
        //countclientAvailableTime=true;
    }
示例#57
0
        public override void SendToSim()
        {
            roll_out     = (float)MainV2.comPort.MAV.cs.hilch1 / rollgain;
            pitch_out    = (float)MainV2.comPort.MAV.cs.hilch2 / pitchgain;
            throttle_out = ((float)MainV2.comPort.MAV.cs.hilch3) / throttlegain;
            rudder_out   = (float)MainV2.comPort.MAV.cs.hilch4 / ruddergain;

            // Limit min and max
            roll_out     = Constrain(roll_out, -1, 1);
            pitch_out    = Constrain(pitch_out, -1, 1);
            rudder_out   = Constrain(rudder_out, -1, 1);
            throttle_out = Constrain(throttle_out, 0, 1);

            // sending only 1 packet instead of many.

            byte[] Xplane = new byte[5 + 36 + 36];

            if (heli)
            {
                Xplane = new byte[5 + 36 + 36 + 36];
            }

            Xplane[0] = (byte)'D';
            Xplane[1] = (byte)'A';
            Xplane[2] = (byte)'T';
            Xplane[3] = (byte)'A';
            Xplane[4] = 0;

            Array.Copy(BitConverter.GetBytes((int)25), 0, Xplane, 5, 4);             // packet index

            Array.Copy(BitConverter.GetBytes((float)throttle_out), 0, Xplane, 9, 4); // start data
            Array.Copy(BitConverter.GetBytes((float)throttle_out), 0, Xplane, 13, 4);
            Array.Copy(BitConverter.GetBytes((float)throttle_out), 0, Xplane, 17, 4);
            Array.Copy(BitConverter.GetBytes((float)throttle_out), 0, Xplane, 21, 4);

            Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, 25, 4);
            Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, 29, 4);
            Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, 33, 4);
            Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, 37, 4);

            // NEXT ONE - control surfaces

            Array.Copy(BitConverter.GetBytes((int)11), 0, Xplane, 41, 4);                        // packet index

            Array.Copy(BitConverter.GetBytes((float)(pitch_out * REV_pitch)), 0, Xplane, 45, 4); // start data
            Array.Copy(BitConverter.GetBytes((float)(roll_out * REV_roll)), 0, Xplane, 49, 4);
            Array.Copy(BitConverter.GetBytes((float)(rudder_out * REV_rudder)), 0, Xplane, 53, 4);
            Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, 57, 4);

            Array.Copy(BitConverter.GetBytes((float)(roll_out * REV_roll * 0.5)), 0, Xplane, 61, 4);
            Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, 65, 4);
            Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, 69, 4);
            Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, 73, 4);

            if (heli)
            {
                Array.Copy(BitConverter.GetBytes((float)(0)), 0, Xplane, 53, 4);


                int a = 73 + 4;
                Array.Copy(BitConverter.GetBytes((int)39), 0, Xplane, a, 4);                      // packet index
                a += 4;
                Array.Copy(BitConverter.GetBytes((float)(12 * collective_out)), 0, Xplane, a, 4); // main rotor 0 - 12
                a += 4;
                Array.Copy(BitConverter.GetBytes((float)(12 * rudder_out)), 0, Xplane, a, 4);     // tail rotor -12 - 12
                a += 4;
                Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, a, 4);
                a += 4;
                Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, a, 4);
                a += 4;
                Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, a, 4);
                a += 4;
                Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, a, 4);
                a += 4;
                Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, a, 4);
                a += 4;
                Array.Copy(BitConverter.GetBytes((int)-999), 0, Xplane, a, 4);
            }

            try
            {
                XplanesSEND.Send(Xplane, Xplane.Length);
            }
            catch (Exception e) { log.Info("Xplanes udp send error " + e.Message); }
        }
示例#58
0
 public void SendMessage(byte[] array)
 {
     _udpClient.Send(array, array.Length);
 }
示例#59
0
        public static IPAddress GetPublicIPAddress(string stunServer)
        {
            try
            {
                logger.LogDebug("STUNClient attempting to determine public IP from " + stunServer + ".");

                using (UdpClient udpClient = new UdpClient(stunServer, DEFAULT_STUN_PORT))
                {
                    STUNMessage initMessage      = new STUNMessage(STUNMessageTypesEnum.BindingRequest);
                    byte[]      stunMessageBytes = initMessage.ToByteBuffer();
                    udpClient.Send(stunMessageBytes, stunMessageBytes.Length);

                    IPAddress        publicIPAddress = null;
                    ManualResetEvent gotResponseMRE  = new ManualResetEvent(false);

                    udpClient.BeginReceive((ar) =>
                    {
                        try
                        {
                            IPEndPoint stunResponseEndPoint = null;
                            byte[] stunResponseBuffer       = udpClient.EndReceive(ar, ref stunResponseEndPoint);

                            if (stunResponseBuffer != null && stunResponseBuffer.Length > 0)
                            {
                                logger.LogDebug("STUNClient Response to initial STUN message received from " + stunResponseEndPoint + ".");
                                STUNMessage stunResponse = STUNMessage.ParseSTUNMessage(stunResponseBuffer, stunResponseBuffer.Length);

                                if (stunResponse.Attributes.Count > 0)
                                {
                                    foreach (STUNAttribute stunAttribute in stunResponse.Attributes)
                                    {
                                        if (stunAttribute.AttributeType == STUNAttributeTypesEnum.MappedAddress)
                                        {
                                            publicIPAddress = ((STUNAddressAttribute)stunAttribute).Address;
                                            logger.LogDebug("STUNClient Public IP=" + publicIPAddress.ToString() + ".");
                                        }
                                    }
                                }
                            }

                            gotResponseMRE.Set();
                        }
                        catch (Exception recvExcp)
                        {
                            logger.LogWarning("Exception STUNClient Receive. " + recvExcp.Message);
                        }
                    }, null);

                    if (gotResponseMRE.WaitOne(STUN_SERVER_RESPONSE_TIMEOUT * 1000))
                    {
                        return(publicIPAddress);
                    }
                    else
                    {
                        logger.LogWarning("STUNClient server response timedout after " + STUN_SERVER_RESPONSE_TIMEOUT + "s.");
                        return(null);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception STUNClient GetPublicIPAddress. " + excp.Message);
                return(null);
                //throw;
            }
        }
示例#60
-25
    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 ();
    }