示例#1
1
        } // End Sub Main 


        private static void UdpListener(int port)
        {
            System.Threading.Tasks.Task.Run(async () =>
            {
                using (var udpClient = new System.Net.Sockets.UdpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port)))
                {
                    while (true)
                    {
                        var receivedResults = await udpClient.ReceiveAsync();
                        var s = string.Format("[{0}] {1}", receivedResults.RemoteEndPoint, System.Text.Encoding.ASCII.GetString(receivedResults.Buffer));
                        System.Console.WriteLine(s);
                    }
                } // End Using

            }); // End Task.Run

        } // End Sub UdpListener
示例#2
0
 /// <summary>Sends a UDP message to the specified IP address and Port.</summary>
 /// <param name="mySendIP">IP address to send the data to.</param>
 /// <param name="myClient">The UDP Client to send to.</param>
 /// <param name="mySendPort">Port to send the data on.</param>
 public async void SendUdp(System.Net.Sockets.UdpClient myClient, System.Net.IPAddress mySendIP, int mySendPort)
 {
     try {
         System.Net.IPEndPoint myEndPoint = new System.Net.IPEndPoint(mySendIP, mySendPort);
         await myClient.SendAsync(Buffer, BytePeek, myEndPoint);
     } catch (System.Exception) {}
 }
示例#3
0
 static private IPAddress GetGoogleDnsAddress()
 {
     using (var googleDns = new System.Net.Sockets.UdpClient("8.8.8.8", 53))
     {
         return ((IPEndPoint) googleDns.Client.LocalEndPoint).Address;
     }
 }
示例#4
0
        private void SendSingleMessage(System.Net.Sockets.UdpClient Socket, byte[] Data)
        {
            //Sends the first byte
            Socket.Send(new byte[] {
                Data[0],
                0x0
            }, 2);
            if (Data.Length > 1)
            {
                //Waits the necessary amount of time before sending the second and third bytes
                Thread.Sleep(100);

                byte P1 = Data[1];
                byte P2;
                if (Data.Length > 2)//In case there are only 2 parts
                {
                    P2 = Data[2];
                }
                else
                {
                    P2 = 0x00;
                }
                Socket.Send(new byte[] {
                    P1,
                    P2
                }, 2);
            }
        }
示例#5
0
        public BytesLogWriteManger()
        {
            var ip = GetAppSettings("远程日志IP");
            int number;

            if (!string.IsNullOrEmpty(ip))
            {
                if (GetAppSettings("远程日志端口", out number))
                {
                    _romteEp   = new IPEndPoint(IPAddress.Parse(ip), number);
                    _udpClient = new System.Net.Sockets.UdpClient();
                }
            }
            FileWrite      = new FileWriteManger(ExceptionHander);
            ConvertManager = new BytesConvertManager(Write, ExceptionHander);
            if (GetAppSettings("禁用报文日志", out number) && number == 1)
            {
                IsEnable = false;
            }
            else
            {
                IsEnable = true;
            }
            Root   = "logs";
            Suffix = ".log";
        }
示例#6
0
        public Plugin_UdpClientGui()
            : base("Plugin_UdpClient", "Gui zum versenden von UDP-Paketen")
        {
            InitializeComponent();

            this.udp = new System.Net.Sockets.UdpClient();
        }
示例#7
0
        public static void WriteLog(string sApplicationName, string sMsg)
        {
            lock (typeof(CarverLabUtility.Logger))
            {
                string FILENAME = @"c:\" + sApplicationName + ".log";
                System.IO.StreamWriter fsw;
                string sOut = "[" + System.DateTime.Now.ToString("G") + "] " + sMsg;

                if (System.IO.File.Exists(FILENAME))
                {
                    fsw = System.IO.File.AppendText(FILENAME);
                }
                else
                {
                    fsw = System.IO.File.CreateText(FILENAME);
                }
                fsw.WriteLine(sOut);
                fsw.Close();
                System.Diagnostics.Trace.WriteLine(sMsg);

                System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback,61288);
                System.Net.Sockets.UdpClient uc = new System.Net.Sockets.UdpClient(System.Net.Sockets.AddressFamily.InterNetwork);
                uc.Send(System.Text.Encoding.ASCII.GetBytes(sOut),sOut.Length,ipep);
            }
        }
示例#8
0
        static void RunServer()
        {
            System.Net.IPEndPoint anyIP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
            System.Net.Sockets.UdpClient udpListener = new System.Net.Sockets.UdpClient(514);
            byte[] bReceive; string sReceive; string sourceIP;

            /* Main Loop */
            /* Listen for incoming data on udp port 514 (default for SysLog events) */
            while (true)
            {
                try
                {
                    bReceive = udpListener.Receive(ref anyIP);
                    
                    // Convert incoming data from bytes to ASCII
                    sReceive = System.Text.Encoding.ASCII.GetString(bReceive);
                    
                    // Get the IP of the device sending the syslog
                    sourceIP = anyIP.Address.ToString();

                    // Start a new thread to handle received syslog event
                    new System.Threading.Thread(new logHandler(sourceIP, sReceive).handleLog).Start();
                    
                }
                catch (System.Exception ex) 
                { 
                    System.Console.WriteLine(ex.ToString()); 
                }
            } // Whend

        } // End Sub Main 
        static StackObject *Send_2(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 5);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Int32 @port = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String @hostname = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Int32 @bytes = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 4);
            System.Byte[] @dgram = (System.Byte[]) typeof(System.Byte[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 5);
            System.Net.Sockets.UdpClient instance_of_this_method = (System.Net.Sockets.UdpClient) typeof(System.Net.Sockets.UdpClient).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.Send(@dgram, @bytes, @hostname, @port);

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method;
            return(__ret + 1);
        }
示例#10
0
        public void Init(string ipOrHost, int port)
        {
            this.ipOrHost = ipOrHost;
            this.port     = port;

            try
            {
                System.Net.IPAddress localAddress = System.Net.IPAddress.Parse(ipOrHost);

                //UdpClientを作成し、ローカルエンドポイントにバインドする
                System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(localAddress, port);
                this.udp = new System.Net.Sockets.UdpClient(localEP);
            }
            catch (Exception e)
            {
                if (ErrorLogHandler != null)
                {
                    ErrorLogHandler(this, e.ToString());
                }
                return;
            }
            if (LogHandler != null)
            {
                LogHandler(this, String.Format("Connected to the {0}:{1}. ", ipOrHost, port));
            }

            if (ReceiveHandler == null)
            {
                return;
            }
            this.threadActive = true;
            this.thread       = new System.Threading.Thread(new System.Threading.ThreadStart(ReceiveProc));
            this.thread.Start();
        }
示例#11
0
 void ReceiveCallback(IAsyncResult ar)
 {
     Console.WriteLine("rec:s");
     //受信中止
     System.Net.Sockets.UdpClient localClient = (System.Net.Sockets.UdpClient)ar.AsyncState;
     System.Net.IPEndPoint        remoteEP    = null;
     byte[] recieveData;
     try
     {
         recieveData = localClient.EndReceive(ar, ref remoteEP);
         UDP_PACKETS_CODER.UDP_PACKETS_DECODER dec = new UDP_PACKETS_CODER.UDP_PACKETS_DECODER();
         dec.Source = recieveData;
         if (dec.get_bool())
         {
             //アクセス要求が来たら返信
             this.MakeNewLocalClient(remoteEP);
         }
     }
     catch (Exception ex)
     {
         Console.Write(ex.Message);
         return;
     }
     //受信再開
     localClient.BeginReceive(ReceiveCallback, localClient);
 }
示例#12
0
 void setup()
 {
     //接続
     System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(this.myIP), this.myPort);
     this.client = new System.Net.Sockets.UdpClient(localEP);
     this.client.BeginReceive(this.ReceiveCallBack, this.client);
 }
示例#13
0
文件: FormMain.cs 项目: lstasi/polipw
        private uint count = 0;              //Counter times of socket realese with no data in



        public FormMain()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            this.UdpIn     = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
            this.UdpOut    = new System.Net.Sockets.UdpClient();
            BufferINSocket = new BufferIN();

            this.UdpIn.Blocking = false;                    //Socket don't block on recive
            this.UdpIn.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 20002));
            this.UdpIn.SetSocketOption(System.Net.Sockets.SocketOptionLevel.IP, System.Net.Sockets.SocketOptionName.AddMembership, new System.Net.Sockets.MulticastOption(System.Net.IPAddress.Parse("230.0.0.2")));

            this.BufferINSocket.OnNewData += new System.EventHandler(this.OnNewData_Event);
            this.BufferINSocket.OnError   += new System.EventHandler(this.OnError_Event);

            this.timerSocket.Tick += new System.EventHandler(this.timerSocket_Tick);
            this.SetStyle(System.Windows.Forms.ControlStyles.StandardClick, true);


            Screen Pantalla = System.Windows.Forms.Screen.PrimaryScreen;

            System.Drawing.Rectangle ScreenBound = Pantalla.Bounds;
            this.SetDesktopLocation(ScreenBound.Width - this.Width - 25, 25);
            this.toolTipDobleClick.SetToolTip(this, "DoubleClick->Minimize");
            this.toolTipDobleClick.SetToolTip(this.progressBarSpeed, "DoubleClick->Minimize");

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
示例#14
0
        /// <summary>
        /// 连接某IP的端口
        /// </summary>
        /// <param name="ip">要连接的ip</param>
        /// <param name="port">要连接的端口</param>
        /// <returns>连上返回true,否则false</returns>
        private bool IsConnet(string ip, int port)
        {
            bool tcpListen = false;
            bool udpListen = false;//设定端口状态标识位

            System.Net.IPAddress  myIpAddress  = System.Net.IPAddress.Parse(ip);
            System.Net.IPEndPoint myIpEndPoint = new System.Net.IPEndPoint(myIpAddress, port);
            try
            {
                System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient();
                tcpClient.Connect(myIpEndPoint);//对远程计算机的指定端口提出TCP连接请求
                tcpListen = true;
            }
            catch { }
            try
            {
                System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient();
                udpClient.Connect(myIpEndPoint);//对远程计算机的指定端口提出UDP连接请求
                udpListen = true;
            }
            catch { }
            if (tcpListen == false || udpListen == false)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
示例#15
0
        public DateTime GetTime()
        {
            try
            {
                // NTPサーバへの接続用UDP生成
                var ip  = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
                var udp = new System.Net.Sockets.UdpClient(ip);

                // NTPサーバへのリクエスト送信
                var sendData = new Byte[48];
                sendData[0] = 0xB;
                udp.Send(sendData, 48, "time.windows.com", 123);

                // NTPサーバから日時データ受信
                var receiveData = udp.Receive(ref ip);

                // 1900年1月1日からの経過秒数計算
                var totalSeconds = (long)(
                    receiveData[40] * Math.Pow(2, (8 * 3)) +
                    receiveData[41] * Math.Pow(2, (8 * 2)) +
                    receiveData[42] * Math.Pow(2, (8 * 1)) +
                    receiveData[43]);

                var utcTime = new DateTime(1900, 1, 1).AddSeconds(totalSeconds);

                // 協定世界時 (UTC) からローカルタイムゾーンへの変更
                var localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.Local);
                return(localTime);
            }
            catch
            {
                return(System.DateTime.Now);
            }
        }
示例#16
0
        //UDPパケットを受け付け開始
        private async Task StartReceiveAudioPacketAsync(BufferedWaveProvider provider)
        {
            //G.722コーデックを用意
            var codec      = new NAudio.Codecs.G722Codec();
            var codecState = new NAudio.Codecs.G722CodecState(64000, NAudio.Codecs.G722Flags.None);

            //UdpClientを作成し、ローカルエンドポイントにバインドする
            var localEP = new IPEndPoint(IPAddress.Any, LocalPort);

            using (var udp = new System.Net.Sockets.UdpClient(localEP))
            {
                IPEndPoint remoteEP = null;

                for (;;)
                {
                    //データを受信する
                    while (udp.Available > 0)
                    {
                        byte[]  rcvBytes      = udp.Receive(ref remoteEP);
                        short[] bufferedData  = new short[350];
                        int     bufferdLength = codec.Decode(codecState, bufferedData, rcvBytes, rcvBytes.Length);
                        byte[]  bufferdBytes  = ConvertShortTo16Bit(bufferedData, bufferdLength);

                        //バッファに追加
                        provider.AddSamples(bufferdBytes, 0, bufferdBytes.Length);
                    }
                    await Task.Delay(10);
                }
            }
        }
示例#17
0
 static private IPAddress GetGoogleDnsAddress()
 {
     using (var googleDns = new System.Net.Sockets.UdpClient("8.8.8.8", 53))
     {
         return(((IPEndPoint)googleDns.Client.LocalEndPoint).Address);
     }
 }
示例#18
0
        public UdpClient(string ipAddress)
        {
            Port = ipAddress.HashCode();
            var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), Port);

            client = new System.Net.Sockets.UdpClient(endpoint);
        }
示例#19
0
        private static async Task Discover()
        {
            using (var server = new System.Net.Sockets.UdpClient(8888))
            {
                var responseData = System.Text.Encoding.ASCII.GetBytes($"port: {Port}|id: {ServerId:D}");

                while (!_stopping)
                {
                    try
                    {
                        var clientRequestData = await server.ReceiveAsync(); // (ref clientEp);

                        var clientRequest = System.Text.Encoding.ASCII.GetString(clientRequestData.Buffer);
                        if (clientRequest == "sync-service")
                        {
                            Console.WriteLine("Request from {0}, sending discover response", clientRequestData.RemoteEndPoint.Address);
                            await server.SendAsync(responseData, responseData.Length, clientRequestData.RemoteEndPoint);
                        }
                        else
                        {
                            Console.WriteLine("Request from {0} invalid {1}", clientRequestData.RemoteEndPoint.Address, clientRequest);
                            await server.SendAsync(responseData, responseData.Length, clientRequestData.RemoteEndPoint);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Failed on discovery: {e}");
                        await Task.Delay(2000);
                    }
                }
            }
        }
示例#20
0
        /// <summary>
        /// 运行程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (button1.Content.ToString() == "停止运行")
            {
                foreach (var item in states)
                {
                    //释放内存
                    ((Timer)item.UserToKen).Dispose();
                    if (!item.CurrentProcess.HasExited)
                    {
                        item.CurrentProcess.Kill();
                    }
                }
                try
                {
                    //移除组播
                    udp.DropMulticastGroup(System.Diagnostics.UDPGroup.group.ep.Address);
                    udp.Close();

                    states.Clear();
                    task.Dispose();
                }
                catch (Exception ex)
                {
                }
                button1.Content = "开始运行";
            }
            else
            {
                //当前已经采集的索引
                if (System.IO.File.Exists(ProgressFileName))
                {
                    List <string> arr = System.IO.File.ReadLines(ProgressFileName).ToList();
                    foreach (var item in Strs)
                    {
                        //得到当前项的状态如果包含则将当前项设置为 true 表示已经处理过了
                        if (arr.Contains(item.Key))
                        {
                            item.Value.IsCollectioned = true;
                        }
                    }
                }
                //初始化采集进程
                System.Linq.Enumerable.Range(0, MaxPorcess).ToList().ForEach((p) =>
                {
                    System.Threading.Thread.Sleep(40);
                    AddStates();
                });


                //开始监听
                task = System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    udp = new System.Net.Sockets.UdpClient(System.Diagnostics.UDPGroup.group.ep.Port);
                    udp.JoinMulticastGroup(System.Diagnostics.UDPGroup.group.ep.Address);
                    udp.BeginReceive(AsyncCallback, udp);
                });
                button1.Content = "停止运行";
            }
        }
示例#21
0
        static void RunServer()
        {
            System.Net.IPEndPoint        anyIP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
            System.Net.Sockets.UdpClient udpListener = new System.Net.Sockets.UdpClient(514);
            byte[] bReceive; string sReceive; string sourceIP;

            /* Main Loop */
            /* Listen for incoming data on udp port 514 (default for SysLog events) */
            while (true)
            {
                try
                {
                    bReceive = udpListener.Receive(ref anyIP);

                    // Convert incoming data from bytes to ASCII
                    sReceive = System.Text.Encoding.ASCII.GetString(bReceive);

                    // Get the IP of the device sending the syslog
                    sourceIP = anyIP.Address.ToString();

                    // Start a new thread to handle received syslog event
                    new System.Threading.Thread(new logHandler(sourceIP, sReceive).handleLog).Start();
                }
                catch (System.Exception ex)
                {
                    System.Console.WriteLine(ex.ToString());
                }
            } // Whend
        }     // End Sub Main
示例#22
0
        static void Main(string[] args)
        {
            //specify char code
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            //locak port number to bind
            int localPort = 9750;

            //binding localPort
            System.Net.Sockets.UdpClient udp =
                new System.Net.Sockets.UdpClient(localPort);

            //データを受信する
            System.Net.IPEndPoint remoteEP = null;
            while (true)
            {
                byte[] rcvBytes = udp.Receive(ref remoteEP);
                string rcvMsg = enc.GetString(rcvBytes);
                OutputString(string.Format("received:{0}", rcvMsg));
                OutputString(string.Format("source address:{0}/port:{1}",
                    remoteEP.Address, remoteEP.Port));
            }
            //close UDP connection
            udp.Close();

            //Console.ReadLine();
        }
示例#23
0
 private void Form1_Load(object sender, EventArgs e)
 {
     udpcMiio             = new System.Net.Sockets.UdpClient();
     thrMiio              = new System.Threading.Thread(ReceiveMessage);
     thrMiio.IsBackground = true;
     thrMiio.Start();
 }
        public Device(
            System.Action <string> log,
            System.Action <string> logWithEol)
        {
            this.log    = log;
            this.logEol = logWithEol;

            this.btData    = new byte[1];
            this.btData[0] = 83;
            this.btBuffer  = this.btData.AsBuffer();

            for (int i = 0; i < (8 * 3); i++)
            {
                this.data[i] = 0;
            }

            this.udp = new System.Net.Sockets.UdpClient();
            this.udp.Connect("localhost", 4242);
            this.receiver = new ReceiverStateMachine(this.SetX, this.SetY, this.SetZ);

            if (!this.BluetoothSetup())
            {
                throw new System.Exception("Could not connect to bluetooth device. Make sure it is paired and connected.");
            }
        }
示例#25
0
        private void Open()
        {
            System.Net.Sockets.UdpClient multicastListener = null;

            if (!m_exclusive_port)
            {
                /* We need a shared multicast "listen" port. This is the 0xBAC0 port */
                /* This will enable us to have more than 1 client, on the same machine. Perhaps it's not that important though. */
                /* We (might) only receive the multicast on this. Any unicasts to this might be eaten by another local client */
                if (m_shared_conn == null)
                {
                    m_shared_conn = new Net.Sockets.UdpClient(System.Net.Sockets.AddressFamily.InterNetworkV6);
                    m_shared_conn.ExclusiveAddressUse = false;
                    m_shared_conn.Client.SetSocketOption(Net.Sockets.SocketOptionLevel.Socket, Net.Sockets.SocketOptionName.ReuseAddress, true);
                    System.Net.EndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.IPv6Any, m_port);
                    if (!string.IsNullOrEmpty(m_local_endpoint))
                    {
                        ep = new System.Net.IPEndPoint(Net.IPAddress.Parse(m_local_endpoint), m_port);
                    }
                    m_shared_conn.Client.Bind(ep);

                    multicastListener = m_shared_conn;
                }
                /* This is our own exclusive port. We'll recieve everything sent to this. */
                /* So this is how we'll present our selves to the world */
                if (m_exclusive_conn == null)
                {
                    System.Net.EndPoint ep = new Net.IPEndPoint(System.Net.IPAddress.IPv6Any, 0);
                    if (!string.IsNullOrEmpty(m_local_endpoint))
                    {
                        ep = new Net.IPEndPoint(Net.IPAddress.Parse(m_local_endpoint), 0);
                    }
                    m_exclusive_conn = new Net.Sockets.UdpClient((Net.IPEndPoint)ep);
                }
            }
            else
            {
                System.Net.EndPoint ep = new Net.IPEndPoint(System.Net.IPAddress.IPv6Any, m_port);
                if (!string.IsNullOrEmpty(m_local_endpoint))
                {
                    ep = new Net.IPEndPoint(Net.IPAddress.Parse(m_local_endpoint), m_port);
                }
                m_exclusive_conn = new Net.Sockets.UdpClient(System.Net.Sockets.AddressFamily.InterNetworkV6);
                m_exclusive_conn.ExclusiveAddressUse = true;
                m_exclusive_conn.Client.Bind((Net.IPEndPoint)ep);

                multicastListener = m_exclusive_conn;
            }

            multicastListener.JoinMulticastGroup(IPAddress.Parse("[FF02::BAC0]"));
            multicastListener.JoinMulticastGroup(IPAddress.Parse("[FF04::BAC0]"));
            multicastListener.JoinMulticastGroup(IPAddress.Parse("[FF05::BAC0]"));
            multicastListener.JoinMulticastGroup(IPAddress.Parse("[FF08::BAC0]"));
            multicastListener.JoinMulticastGroup(IPAddress.Parse("[FF0E::BAC0]"));

            // If this option is enabled Yabe cannot see itself !
            // multicastListener.MulticastLoopback = false;

            bvlc = new BVLCV6(this, m_VMac);
        }
示例#26
0
 //アクセス要求
 void AccessReceiveCallback(IAsyncResult ar)
 {
     Console.WriteLine("rec:c");
     //受信中止
     System.Net.Sockets.UdpClient client   = (System.Net.Sockets.UdpClient)ar.AsyncState;
     System.Net.IPEndPoint        remoteEP = null;
     byte[] recieveData;
     try
     {
         recieveData = client.EndReceive(ar, ref remoteEP);
         UDP_PACKETS_CODER.UDP_PACKETS_DECODER dec = new UDP_PACKETS_CODER.UDP_PACKETS_DECODER();
         dec.Source = recieveData;
         bool state = dec.get_bool();
         if (state)
         {
             //サーバーが返したポートに接続しなおし
             this.MakeNewClient(dec.get_int(), dec.get_int());
             this.IsAccessed = true;
         }
     }
     catch (Exception ex)
     {
         Console.Write(ex.Message);
         return;
     }
     //受信再開
     if (!this.IsAccessed)
     {
         client.BeginReceive(this.AccessReceiveCallback, client);
     }
 }
 public UdpListener(int listenPort = 31173)
 {
     UDP = new System.Net.Sockets.UdpClient(listenPort);
     JSS = new JsonSerializerSettings()
     {
         ContractResolver = new CamelCasePropertyNamesContractResolver()
     };
 }
示例#28
0
 void setup()
 {
     //接続
     System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(this.myIP), this.myPort);
     this.client = new System.Net.Sockets.UdpClient(localEP);
     this.client.BeginReceive(this.AccessReceiveCallback, this.client);
     Console.WriteLine("clientaut");
 }
示例#29
0
        public static System.Net.Sockets.UdpClient GetBroadcastReceiver(System.Net.IPEndPoint clientEndpoint)
        {
            System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient();
            udpClient.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReuseAddress, true);
            udpClient.Client.Bind(clientEndpoint);

            return(udpClient);
        }
示例#30
0
        private static System.Net.Sockets.UdpClient BroadcastClient()
        {
            System.Net.Sockets.UdpClient client =
                new System.Net.Sockets.UdpClient();

            client.EnableBroadcast = true;
            return(client);
        }
示例#31
0
        static void Main(string[] args)
        {
            var udpClient = new System.Net.Sockets.UdpClient();
            udpClient.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 9500));
            udpClient.Send(new byte[] { 1, 0, 0, 0, 8 }, 5);

            Console.ReadLine();
        }
 public GameServerLogicForPlayer(System.Net.Sockets.UdpClient udpClient)
 {
     _cancellationTokenSource                    = new System.Threading.CancellationTokenSource();
     _myUdpClient                                = udpClient;
     _gameServerMessenger                        = new GameCom.ClientMessenger(_myUdpClient, _cancellationTokenSource.Token);
     _gameServerMessenger.SocketEventInfo       += _gameServerMessenger_SocketEventInfo;
     GameCom.ClientMessenger.ReceivedDataLog    += ClientMessenger_ReceivedDataLog;
     _gameServerMessenger.HandleRecievedMessage += HandleRecievedMessage;
 }
示例#33
0
        private void ReceiveResult(IAsyncResult ar)
        {
            socket = (System.Net.Sockets.UdpClient)ar.AsyncState;
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);

            recvBuffer = socket.EndReceive(ar, ref remote);
            dataPacker.UnPack(recvBuffer);
            socket.BeginReceive(ReceiveResult, socket);
        }
示例#34
0
 private void SendData()
 {
     System.Net.Sockets.UdpClient _sockMain = new System.Net.Sockets.UdpClient(IP, Port);
     while (issending)
     {
         // Define and assign arr_bData somewhere in class
         _sockMain.Send(arr_bData, arr_bData.Length);
     }
 }
示例#35
0
        private static void Startup()
        {
            // The chat server always starts up on the localhost, using the default port
            IPHostEntry hostInfo   = Dns.GetHostByName(DEFAULT_SERVER);
            IPAddress   serverAddr = hostInfo.AddressList[0];

            serverEndPoint = new IPEndPoint(serverAddr, DEFAULT_PORT);
            udpServer      = new System.Net.Sockets.UdpClient();
        }
示例#36
0
        public async Task <int> SendAsync(byte[] data)
        {
            using (var udpClient = new System.Net.Sockets.UdpClient())
            {
                var result = await udpClient.SendAsync(data, data.Length, host, port).ConfigureAwait(false);

                return(result);
            }
        }
示例#37
0
        private static void Main(string[] args)
        {
            byte[] toDisplay = null;

            var consoleUpdater = Task.Run(async() =>
            {
                while (true)
                {
                    if (toDisplay != null)
                    {
                        Console.SetCursorPosition(0, 0);
                        Console.Write(StatusScreen(toDisplay));
                        toDisplay = null;
                    }

                    await Task.Delay(300);
                }
            });


            var ipEndPoint   = new IPEndPoint(IPAddress.Loopback, FORZA_DATA_OUT_PORT);
            var senderClient = new System.Net.Sockets.UdpClient(FORZA_HOST_PORT);
            var senderTask   = Task.Run(async() =>
            {
                while (true)
                {
                    Console.WriteLine("Sending heartbeat");
                    await senderClient.SendAsync(new byte[1], 1, ipEndPoint);
                    await Task.Delay(5000);
                }
            });

            var receiverTask = Task.Run(async() =>
            {
                Console.Clear();
                var client = new System.Net.Sockets.UdpClient(FORZA_DATA_OUT_PORT);
                Console.WriteLine("Listening... ");
                while (true)
                {
                    await client.ReceiveAsync().ContinueWith(receive =>
                    {
                        var resultBuffer = receive.Result.Buffer;
                        if (resultBuffer.Length != 311 || toDisplay != null)
                        {
                            return;
                        }

                        var stuff = new byte[resultBuffer.Length];
                        resultBuffer.CopyTo(stuff, 0);
                        toDisplay = stuff;
                    });
                }
            });


            Task.WaitAll(senderTask, receiverTask, consoleUpdater);
        }
示例#38
0
		public bool Close()
		{
			bool result;
			if (result = this.backend.NotNull())
			{
				this.backend.Close();
				this.backend = null;
			}
			return result;
		}
示例#39
0
        /// <summary>
        /// Starts listening for incoming connections
        /// </summary>
        public override void Start()
        {
            if (Running)
                return;

            //TODO test if it is better to use socket directly
            //Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            
            listener = new System.Net.Sockets.UdpClient(endpoint.Port);
            listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
        }
示例#40
0
文件: Client.cs 项目: jaxohua/fsi
        static void Main(string[] args)
        {
            System.Net.Sockets.UdpClient sock = new System.Net.Sockets.UdpClient();
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 15000);
            byte[] data = Encoding.ASCII.GetBytes("Hola Servidor UDP!!");
            sock.Send(data, data.Length, iep);
            sock.Close();

            Console.WriteLine("Mensaje enviado.");
            Console.ReadLine();
        }
示例#41
0
        public static NTPData Test(IPAddress ntpServer)
        {
            var data = MarshalExtend.GetData(new NTPData());

            var udp = new System.Net.Sockets.UdpClient();
            udp.Send(data, data.Length, new IPEndPoint(ntpServer, 123));

            var ep = new IPEndPoint(IPAddress.Any, 0);
            var replyData = udp.Receive(ref ep);

            return MarshalExtend.GetStruct<NTPData>(replyData, replyData.Length);
        }
示例#42
0
 private static void send_packet( string data_package )
 {
     var magic_packet = new System.Net.Sockets.UdpClient( );
     try {
         magic_packet.Connect( System.Net.IPAddress.Broadcast, 9 );
         var dgram = hex_string_to_byte( data_package );
         magic_packet.Send( dgram, dgram.Length );
         magic_packet.Close( );
     } catch( Exception e ) {
         MessageBox.Show( string.Format( "Exception while sending packet: {0}", e.Message ) );
     }
 }
示例#43
0
        public static void Broadcast()
        {
            byte[] bytes = new byte[NAEHandler.BroadcastMessage.Length + 2];
            Encoding.ASCII.GetBytes(NAEHandler.BroadcastMessage, 0, NAEHandler.BroadcastMessage.Length, bytes, 0);
            BitConverter.GetBytes((ushort)0).CopyTo(bytes, NAEHandler.BroadcastMessage.Length);

            System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient();
            System.Net.IPEndPoint groupEP = new System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, NAEHandler.BroadcastPort);

            client.Send(bytes, bytes.Length, groupEP);
            client.Close();
        }
示例#44
0
        public UdpClient(string multicastIp, int port, IJsonProvider json)
        {
            var ip = IPAddress.Parse(multicastIp);
            _endPoint = new IPEndPoint(ip, port);
            _udpClient = new System.Net.Sockets.UdpClient(port);
            _udpClient.JoinMulticastGroup(ip);

            _timer = new Timer(30 * 1000); // 30 seconds
            _timer.AutoReset = true;
            _timer.Elapsed += Broadcast;

            _json = json;
        }
示例#45
0
文件: Server.cs 项目: jaxohua/fsi
        static void Main(string[] args)
        {
            System.Net.Sockets.UdpClient server = new System.Net.Sockets.UdpClient(15000);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            byte[] data = new byte[1024];
            data = server.Receive(ref sender);
            server.Close();
            string stringData = Encoding.ASCII.GetString(data, 0, data.Length);

            Console.WriteLine("Respondiendo desde " + sender.Address + Environment.NewLine + "Mensaje: " + stringData);
            Console.ReadLine();
        }
 public Connection Connect()
 {
     try
     {
         System.Net.Sockets.UdpClient socket = new System.Net.Sockets.UdpClient(port);
         System.Net.IPAddress groupAddress = System.Net.Dns.GetHostEntry(group).AddressList[0];
         socket.JoinMulticastGroup((System.Net.IPAddress) groupAddress);
         return new MulticastConnection(socket, groupAddress);
     }
     catch (System.IO.IOException e)
     {
         throw new FastConnectionException(e);
     }
 }
示例#47
0
        public void Send(byte[] data)
        {
            //クライアントがなければ作る
            try
            {
                if (this.client == null)
                    this.client = new System.Net.Sockets.UdpClient();
                this.client.BeginSend(data, data.Length, this.serverIP, this.serverPort, this.sendCallBack, this.client);
            }
            catch
            {

            }
        }
示例#48
0
        private static System.Net.NetworkInformation.PhysicalAddress GetMacAddress()
        {
            var googleDns = new System.Net.Sockets.UdpClient("8.8.8.8", 53);
            IPAddress localAddr = ((IPEndPoint)googleDns.Client.LocalEndPoint).Address;

            foreach (var netInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
            {
                foreach (var addr in netInterface.GetIPProperties().UnicastAddresses)
                {
                    if (addr.Address.Equals(localAddr))
                        return netInterface.GetPhysicalAddress();
                }
            }
            return null;
        }
示例#49
0
 /// <summary>
 /// Initializes a new UdpServer class.
 /// </summary>
 public UdpServer()
 {
     _packageListeners = new List<IPackageListener>();
     _connections = new List<IConnection>();
     _logger = LogManager.GetClassLogger();
     _connectionManager = new UdpConnectionManager();
     _connectionManager.PingTimedOut += _connectionManager_PingTimedOut;
     _connectionManager.Start();
     TimeOutLatency = 500f;
     _listener = new System.Net.Sockets.UdpClient(2563);
     IsActive = true;
     var beginHandle = new Thread(BeginAcceptConnections) {IsBackground = true};
     var pingHandle = new Thread(PingRequestLoop) {IsBackground = true};
     beginHandle.Start();
     pingHandle.Start();
 }
        static void Main(string[] args)
        {
            t = new System.Timers.Timer();
            t.Interval = 1000;
            t.Elapsed += T_Elapsed;

            try
            {
                System.Net.IPEndPoint groupEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any,5001);
                System.Net.Sockets.UdpClient listener = new System.Net.Sockets.UdpClient(groupEP);
                Console.WriteLine("\rPackets Recd: ");
                Console.WriteLine("\rTime: " + " Seconds");
                Console.WriteLine("\rMoving Avg:\t  Bytes/sec");
                Console.WriteLine("\rTotal Avg:\t  Bytes/sec");
                Console.WriteLine("\rMax:\t Bytes/sec");
                Console.WriteLine("\rMin:\t Bytes/sec");
                while (listener.Receive(ref groupEP).Length == 0)
                {}
                startTime = DateTime.Now;
                bytesRec = 0;
                t.Start();
                byte[] data;
                while (true)
                {
                    data = listener.Receive(ref groupEP);

                    bytesRec += data.Length;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("FATAL EXCEPTION!");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Press enter to exit");
                Console.ReadLine();
            }
        }
示例#51
0
文件: Network.cs 项目: Genjo15/Snake
        private System.Net.Sockets.UdpClient _Socket; // The socket (for sending data / receiving data, depends on the context)

        #endregion Fields

        #region Constructors

        /*
         * Constructor of Network
         *      - Initialize variables.
         *      - Bind sockets.
         * */
        public Network(ref NetworkContainer container, Boolean isHost, Boolean forSending, Delegate del)
        {
            _Container = container;
            _IsHost = isHost;
            _HostIpAdress = "";
            _Continue = true;

            _Delegate = del;
            _NetworkDelegate = new networkDelegate(AbortConnection);

            _Socket = new System.Net.Sockets.UdpClient();
            _Socket.EnableBroadcast = false;

            if (forSending)
            {
                _Socket.Client.Bind(new System.Net.IPEndPoint(0, 5000));
                _EndPoint = new System.Net.IPEndPoint(0, 5000);
            }
            else if (!forSending)
            {
                _Socket.Client.Bind(new System.Net.IPEndPoint(0, 5001));
                _EndPoint = new System.Net.IPEndPoint(0, 5001);
            }
        }
示例#52
0
        public void StopMonitoringPortCheck()
        {
            UdpLicensor lic = new UdpLicensor(
                Encoding.UTF8.GetBytes("foo"),
                2,
                15700,
                15701
                );

            lic.IsMonitoring = true;
            Thread.Sleep(200);
            lic.IsMonitoring = false;
            System.Net.Sockets.UdpClient udpc = new System.Net.Sockets.UdpClient(15700);
            udpc.Close();
            udpc = new System.Net.Sockets.UdpClient(15701);
            udpc.Close();
        }
示例#53
0
 static SetGPSIntervalCmd()
 {
     gwClient = new System.Net.Sockets.UdpClient(0);
 }
示例#54
0
 public void Dispose()
 {
     try
     {
         m_exclusive_conn.Close();
         m_exclusive_conn = null;
         m_shared_conn.Close(); // maybe an exception if null
         m_shared_conn = null;
     }
     catch { }
 }
示例#55
0
        private void Open()
        {
            if (!m_exclusive_port)
            {
                /* We need a shared broadcast "listen" port. This is the 0xBAC0 port */
                /* This will enable us to have more than 1 client, on the same machine. Perhaps it's not that important though. */
                /* We (might) only receive the broadcasts on this. Any unicasts to this might be eaten by another local client */
                if (m_shared_conn == null)
                {
                    m_shared_conn = new Net.Sockets.UdpClient();
                    m_shared_conn.ExclusiveAddressUse = false;
                    m_shared_conn.Client.SetSocketOption(Net.Sockets.SocketOptionLevel.Socket, Net.Sockets.SocketOptionName.ReuseAddress, true);
                    System.Net.EndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, m_port);
                    if (!string.IsNullOrEmpty(m_local_endpoint)) ep = new System.Net.IPEndPoint(Net.IPAddress.Parse(m_local_endpoint), m_port);
                    m_shared_conn.Client.Bind(ep);
                    m_shared_conn.DontFragment = m_dont_fragment;
                }
                /* This is our own exclusive port. We'll receive everything sent to this. */
                /* So this is how we'll present our selves to the world */
                if (m_exclusive_conn == null)
                {
                    System.Net.EndPoint ep = new Net.IPEndPoint(System.Net.IPAddress.Any, 0);
                    if (!string.IsNullOrEmpty(m_local_endpoint)) ep = new Net.IPEndPoint(Net.IPAddress.Parse(m_local_endpoint), 0);
                    m_exclusive_conn = new Net.Sockets.UdpClient((Net.IPEndPoint)ep);
                    m_exclusive_conn.DontFragment = m_dont_fragment;
                }
            }
            else
            {
                System.Net.EndPoint ep = new Net.IPEndPoint(System.Net.IPAddress.Any, m_port);
                if (!string.IsNullOrEmpty(m_local_endpoint)) ep = new Net.IPEndPoint(Net.IPAddress.Parse(m_local_endpoint), m_port);
                m_exclusive_conn = new Net.Sockets.UdpClient();
                m_exclusive_conn.ExclusiveAddressUse = true;
                m_exclusive_conn.Client.Bind((Net.IPEndPoint)ep);
                m_exclusive_conn.DontFragment = m_dont_fragment;
            }

            bvlc = new BVLC(this);
        }
示例#56
0
        public void WriteLog(string sMsg)
        {
            m_mutex.WaitOne();
            if (bDebugMode)
            {
                string FILENAME = @"c:\" + sApplicationName + ".log";
                System.IO.StreamWriter fsw;
                string sOut;

                if (m_sContext != string.Empty)
                {
                    sOut = "[" + System.DateTime.Now.ToString("G") + "] " + "(" + m_sContext + ") " + sMsg;
                }
                else
                {
                    sOut = "[" + System.DateTime.Now.ToString("G") + "] " + sMsg;
                }

                if (System.IO.File.Exists(FILENAME))
                {
                    fsw = System.IO.File.AppendText(FILENAME);
                }
                else
                {
                    fsw = System.IO.File.CreateText(FILENAME);
                }
                fsw.WriteLine(sOut);
                fsw.Close();

                System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback,61288);
                System.Net.Sockets.UdpClient uc = new System.Net.Sockets.UdpClient(System.Net.Sockets.AddressFamily.InterNetwork);
                uc.Send(System.Text.Encoding.ASCII.GetBytes(sOut),sOut.Length,ipep);
                System.Diagnostics.Trace.WriteLineIf(bTrace,sMsg);
                System.Console.WriteLine(sMsg);
            }
            m_mutex.ReleaseMutex();
        }
示例#57
0
 private void _sendMsg(object param)
 {
     byte[] message = (param as byte[]);
     using (System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient())
     {
         client.Connect(IP, Port);
         client.Send(message, message.Length);
         if (Delay != 0)
             Thread.Sleep(Delay);
     }
 }
示例#58
0
        private void xInitUdp()
        {
            int portno = 4126;
            if (udpClient != null)
            {
                return;
            }

            //UdpClientを作成し、指定したポート番号にバインドする
            System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, portno);

            udpClient = new System.Net.Sockets.UdpClient(localEP);
            //非同期的なデータ受信を開始する
            udpClient.BeginReceive(ReceiveCallback, udpClient);
            xLog("udp open. port="+portno);
        }
 /// <summary>
 /// 受信スレッドを開始して、通信可能にする.
 /// </summary>
 /// <returns></returns>
 public void start()
 {
     lock (locker)
     {
         if (this.receiveThread != null)
         {
             throw new InvalidOperationException("既に受信スレッド実行中!![port:" + this.port + "]");
         }
         if (this.server != null)
         {
             throw new InvalidOperationException("既に受信サーバ実行中!![port:" + this.port + "]");
         }
         this.isRequestExit = false;
         this.server = new System.Net.Sockets.UdpClient(this.port);
         this.receiveThread = new System.Threading.Thread(threadMain);
         this.isRunning = true;
         this.receiveThread.Start();
     }
 }
 /// <summary>
 /// スレッドを終了し、終了するまで待機する.
 /// </summary>
 public void stop()
 {
     lock (locker)
     {
         if (this.receiveThread == null && this.server == null)
         {
             return;
         }
         else if (this.receiveThread == null || this.server == null)
         {
             throw new InvalidOperationException("不正な状態で終了!![port:" + this.port + "][recvThread:" + this.receiveThread + "][server:" + this.server + "]");
         }
         requestStop();
         this.receiveThread.Join();
         this.server = null;
         this.receiveThread = null;
         this.isRunning = false;
     }
 }