Esempio n. 1
0
        public static void ListenToGameSessions <T>(Action <T, IPEndPoint> callback)
            where T : IBytePacket
        {
            var localEndPoint = new IPEndPoint(IPAddress.Any, Port);

            var socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            socketListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            socketListener.ExclusiveAddressUse = false;
            socketListener.Bind(localEndPoint);

            var threadListen = new Thread(() =>
            {
                try
                {
                    while (Listen)
                    {
                        var buffer = new byte[1024];
                        var data   = new List <byte>();
                        int bytes  = 0;

                        var remoteIp = (EndPoint) new IPEndPoint(IPAddress.Any, 0);

                        do
                        {
                            bytes = socketListener.ReceiveFrom(buffer, ref remoteIp);
                            data.AddRange(buffer);
                        }while (socketListener.Available > 0);

                        var remoteFullIp = remoteIp as IPEndPoint;

                        var response = BytePacket <T> .UnPack(data.ToArray());
                        callback(response, remoteFullIp);
                    }


                    socketListener.Close();
                }
                catch (Exception ex)
                {
                }
            });

            threadListen.Start();
        }
Esempio n. 2
0
        public static void ListenToGameSession <T>(string ip, Action <T, IPEndPoint> callback)
            where T : IBytePacket
        {
            var client = new UdpClient();

            client.ExclusiveAddressUse = false;

            var localEp = new IPEndPoint(IPAddress.Any, Port);

            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            client.ExclusiveAddressUse = false;

            client.Client.Bind(localEp);

            var multicastaddress = IPAddress.Parse(ip);

            client.JoinMulticastGroup(multicastaddress);

            var threadListen = new Thread(() =>
            {
                try
                {
                    while (Listen)
                    {
                        var data     = client.Receive(ref localEp);
                        var response = BytePacket <T> .UnPack(data);
                        callback(response, localEp);

                        //if ((response as GameMulticastPacket).Move != 0)
                        //    Debug.WriteLine("Received " + response.ToString());
                    }

                    client.Close();
                }
                catch (Exception ex)
                {
                }
            });

            threadListen.Start();
        }