Exemplo n.º 1
0
        /// <summary>
        /// 新增客户端事件
        /// </summary>
        /// <param name="obj"></param>
        private void UDPServer_ClientInsertEvent(UdpClientInfo obj)
        {
            if (obj == null)
            {
                return;
            }
            TabPage tabPage = new TabPage(obj.clientname)
            {
                Dock        = DockStyle.Fill,
                ToolTipText = obj.endpoint
            };

            tabPage.Controls.Add(new MyTabPage());
            this.Invoke(new Action(() =>
            {
                this.tabControl1.TabPages.Add(tabPage); //增加TabPage
                this.comBoxClient.Items.Add($"{obj.clientname}");
                this.comBoxClient.SelectedIndex = this.tabControl1.SelectedIndex;
            }));
        }
Exemplo n.º 2
0
    private void Awake()
    {
        ISerializer   serializer    = new JsonNetSerializer();
        UdpClientInfo udpClientInfo = new UdpClientInfo
        {
            ServerIp   = "127.0.0.1",
            ServerPort = 3000,
            ChannelId  = 0
        };
        WorldData           worldData          = new WorldData();
        IModelManagerClient modelManagerClient = new ModelManagerClient(worldData);
        IReplication        worldReplication   = new WorldReplication(worldData, serializer.GetCaster());

        _client         = new UdpClient(udpClientInfo);
        _networkManager = new NetworkManager(_client, serializer, modelManagerClient, worldReplication)
        {
            MillisecondsBetweenSendPacket = 1000
        };
        _presenterManager = new GamePresenter(_viewManager, modelManagerClient);

        _presenterManager.Activate();
    }
Exemplo n.º 3
0
        /// <summary>
        /// Starts the <see cref="UdpServer"/> synchronously and begins accepting client connections asynchronously.
        /// </summary>
        /// <exception cref="InvalidOperationException">Attempt is made to <see cref="Start()"/> the <see cref="UdpServer"/> when it is running.</exception>
        public override void Start()
        {
            if (CurrentState == ServerState.NotRunning)
            {
                int maxSendQueueSize;

                // Initialize if unitialized
                if (!Initialized)
                    Initialize();

                // Overwrite config file if max send queue size exists in connection string.
                if (m_configData.ContainsKey("maxSendQueueSize") && int.TryParse(m_configData["maxSendQueueSize"], out maxSendQueueSize))
                    m_maxSendQueueSize = maxSendQueueSize;

                // Bind server socket to local end-point
                m_udpServer = new TransportProvider<Socket>();
                m_udpServer.SetReceiveBuffer(ReceiveBufferSize);
                m_udpServer.Provider = Transport.CreateSocket(m_configData["interface"], int.Parse(m_configData["port"]), ProtocolType.Udp, m_ipStack, m_allowDualStackSocket);

                // Disable SocketError.ConnectionReset exception from being thrown when the endpoint is not listening
                m_udpServer.Provider.IOControl(SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);

                // Notify that the server has been started successfully
                OnServerStarted();

                if ((object)m_udpServer.Provider.LocalEndPoint != null)
                {
                    m_receiveArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction();
                    m_receiveArgs.SocketFlags = SocketFlags.None;
                    m_receiveArgs.Completed += m_receiveHandler;
                    ReceivePayloadAsync(m_receiveArgs);
                }

                // We process the static list to clients.
                foreach (string clientString in m_configData["clients"].Replace(" ", "").Split(','))
                {
                    try
                    {
                        Match endpoint = Regex.Match(clientString, Transport.EndpointFormatRegex);

                        if (endpoint != Match.Empty)
                        {
                            UdpClientInfo clientInfo;
                            TransportProvider<EndPoint> udpClient = new TransportProvider<EndPoint>();
                            IPEndPoint clientEndpoint = Transport.CreateEndPoint(endpoint.Groups["host"].Value, int.Parse(endpoint.Groups["port"].Value), m_ipStack);

                            udpClient.SetReceiveBuffer(ReceiveBufferSize);
                            udpClient.SetSendBuffer(SendBufferSize);
                            udpClient.Provider = clientEndpoint;

                            // If the IP specified for the client is a multicast IP, subscribe to the specified multicast group.
                            if (Transport.IsMulticastIP(clientEndpoint.Address))
                            {
                                string multicastSource;

                                if (m_configData.TryGetValue("multicastSource", out multicastSource))
                                {
                                    IPAddress sourceAddress = IPAddress.Parse(multicastSource);
                                    IPAddress localAddress = (clientEndpoint.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any);

                                    if (sourceAddress.AddressFamily != clientEndpoint.AddressFamily)
                                        throw new InvalidOperationException(string.Format("Source address \"{0}\" is not in the same IP format as server address \"{1}\"", sourceAddress, clientEndpoint.Address));

                                    if (localAddress.AddressFamily != clientEndpoint.AddressFamily)
                                        throw new InvalidOperationException(string.Format("Local address \"{0}\" is not in the same IP format as server address \"{1}\"", localAddress, clientEndpoint.Address));

                                    MemoryStream membershipAddresses = new MemoryStream();

                                    byte[] serverAddressBytes = clientEndpoint.Address.GetAddressBytes();
                                    byte[] sourceAddressBytes = sourceAddress.GetAddressBytes();
                                    byte[] localAddressBytes = localAddress.GetAddressBytes();

                                    membershipAddresses.Write(serverAddressBytes, 0, serverAddressBytes.Length);
                                    membershipAddresses.Write(sourceAddressBytes, 0, sourceAddressBytes.Length);
                                    membershipAddresses.Write(localAddressBytes, 0, localAddressBytes.Length);

                                    udpClient.MulticastMembershipAddresses = membershipAddresses.ToArray();

                                    // Execute multicast subscribe for specific source
                                    SocketOptionLevel level = clientEndpoint.AddressFamily == AddressFamily.InterNetworkV6 ? SocketOptionLevel.IPv6 : SocketOptionLevel.IP;
                                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.AddSourceMembership, udpClient.MulticastMembershipAddresses);
                                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.MulticastTimeToLive, int.Parse(m_configData["multicastTimeToLive"]));
                                }
                                else
                                {
                                    // Execute multicast subscribe for any source
                                    SocketOptionLevel level = clientEndpoint.AddressFamily == AddressFamily.InterNetworkV6 ? SocketOptionLevel.IPv6 : SocketOptionLevel.IP;
                                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.AddMembership, new MulticastOption(clientEndpoint.Address));
                                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.MulticastTimeToLive, int.Parse(m_configData["multicastTimeToLive"]));
                                }
                            }

                            clientInfo = new UdpClientInfo()
                            {
                                Client = udpClient,
                                SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(),
                                SendLock = new SpinLock(),
                                SendQueue = new ConcurrentQueue<UdpServerPayload>()
                            };

                            clientInfo.SendArgs.RemoteEndPoint = udpClient.Provider;
                            clientInfo.SendArgs.SetBuffer(udpClient.SendBuffer, 0, udpClient.SendBufferSize);
                            clientInfo.SendArgs.Completed += m_sendHandler;

                            m_clientInfoLookup.TryAdd(udpClient.ID, clientInfo);
                            OnClientConnected(udpClient.ID);
                        }
                    }
                    catch (Exception ex)
                    {
                        string errorMessage = string.Format("Unable to connect to client {0}: {1}", clientString, ex.Message);
                        OnClientConnectingException(new Exception(errorMessage, ex));
                    }
                }
            }
            else
            {
                throw new InvalidOperationException("Server is currently running");
            }
        }
Exemplo n.º 4
0
        private TransportProvider<EndPoint> AddUdpClient(EndPoint udpClientEndPoint)
        {
            TransportProvider<EndPoint> udpClient = new TransportProvider<EndPoint>();
            IPEndPoint udpClientIPEndPoint = udpClientEndPoint as IPEndPoint;
            UdpClientInfo udpClientInfo;

            // Set up client
            udpClient.SetReceiveBuffer(ReceiveBufferSize);
            udpClient.SetSendBuffer(SendBufferSize);
            udpClient.Provider = udpClientIPEndPoint;

            // If the IP specified for the client is a multicast IP, subscribe to the specified multicast group.
            if ((object)udpClientIPEndPoint != null && Transport.IsMulticastIP(udpClientIPEndPoint.Address))
            {
                SocketOptionLevel level = udpClientIPEndPoint.AddressFamily == AddressFamily.InterNetworkV6 ? SocketOptionLevel.IPv6 : SocketOptionLevel.IP;
                string multicastSource;

                if (m_configData.TryGetValue("multicastSource", out multicastSource))
                {
                    IPAddress sourceAddress = IPAddress.Parse(multicastSource);
                    IPAddress localAddress = (udpClientIPEndPoint.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any);

                    if (sourceAddress.AddressFamily != udpClientIPEndPoint.AddressFamily)
                        throw new InvalidOperationException($"Source address \"{sourceAddress}\" is not in the same IP format as server address \"{udpClientIPEndPoint.Address}\"");

                    if (localAddress.AddressFamily != udpClientIPEndPoint.AddressFamily)
                        throw new InvalidOperationException($"Local address \"{localAddress}\" is not in the same IP format as server address \"{udpClientIPEndPoint.Address}\"");

                    using (BlockAllocatedMemoryStream membershipAddresses = new BlockAllocatedMemoryStream())
                    {
                        byte[] serverAddressBytes = udpClientIPEndPoint.Address.GetAddressBytes();
                        byte[] sourceAddressBytes = sourceAddress.GetAddressBytes();
                        byte[] localAddressBytes = localAddress.GetAddressBytes();

                        membershipAddresses.Write(serverAddressBytes, 0, serverAddressBytes.Length);
                        membershipAddresses.Write(sourceAddressBytes, 0, sourceAddressBytes.Length);
                        membershipAddresses.Write(localAddressBytes, 0, localAddressBytes.Length);

                        udpClient.MulticastMembershipAddresses = membershipAddresses.ToArray();
                    }

                    // Execute multicast subscribe for specific source
                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.AddSourceMembership, udpClient.MulticastMembershipAddresses);
                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.MulticastTimeToLive, int.Parse(m_configData["multicastTimeToLive"]));
                }
                else
                {
                    // Execute multicast subscribe for any source
                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.AddMembership, new MulticastOption(udpClientIPEndPoint.Address));
                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.MulticastTimeToLive, int.Parse(m_configData["multicastTimeToLive"]));
                }
            }

            // Create client info object
            udpClientInfo = new UdpClientInfo
            {
                Client = udpClient,
                SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(),
                SendLock = new object(),
                SendQueue = new ConcurrentQueue<UdpServerPayload>()
            };

            udpClientInfo.DumpPayloadsOperation = new ShortSynchronizedOperation(() =>
            {
                UdpServerPayload payload;

                // Check to see if the client has reached the maximum send queue size.
                if (m_maxSendQueueSize > 0 && udpClientInfo.SendQueue.Count >= m_maxSendQueueSize)
                {
                    for (int i = 0; i < m_maxSendQueueSize; i++)
                    {
                        if (udpClientInfo.SendQueue.TryDequeue(out payload))
                        {
                            payload.WaitHandle.Set();
                            payload.WaitHandle.Dispose();
                            payload.WaitHandle = null;
                        }
                    }

                    throw new InvalidOperationException($"Client {udpClientInfo.Client.ID} connected to UDP server reached maximum send queue size. {m_maxSendQueueSize} payloads dumped from the queue.");
                }
            }, ex => OnSendClientDataException(udpClientInfo.Client.ID, ex));

            // Set up SocketAsyncEventArgs
            udpClientInfo.SendArgs.RemoteEndPoint = udpClient.Provider;
            udpClientInfo.SendArgs.SetBuffer(udpClient.SendBuffer, 0, udpClient.SendBufferSize);
            udpClientInfo.SendArgs.Completed += m_sendHandler;

            // Add new client to the lookup
            m_clientInfoLookup.TryAdd(udpClient.ID, udpClientInfo);
            OnClientConnected(udpClient.ID);

            return udpClient;
        }
Exemplo n.º 5
0
        /// <summary>
        /// 接收发送给本机ip对应端口号的数据报
        /// </summary>
        public void ReciveMsg(CancellationToken token)
        {
            Task.Factory.StartNew(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    EndPoint point = new IPEndPoint(IPAddress.Any, 0);      //用来保存发送方的ip和端口号
                    byte[] buffer  = new byte[2 * 1024];                    //给2*1024个字节作为缓存
                    int length     = server.ReceiveFrom(buffer, ref point); //接收数据报
                    string message = Encoding.UTF8.GetString(buffer, 0, length);
                    InMsg imsg     = JsonConvert.DeserializeObject <InMsg>(message);
                    if (imsg == null)
                    {
                        break;
                    }
                    if (imsg.Type.Equals("INFO") || imsg.Type.Equals("WARN") || imsg.Type.Equals("ERROR") || imsg.Type.Equals("FATAL") || imsg.Type.Equals("DEBUG"))
                    {
                        UdpClientInfo client = new UdpClientInfo()
                        {
                            endpoint   = point.ToString(),
                            clientname = imsg.Client
                        };
                        if (!clients.Any(p => p.endpoint.Equals(client.endpoint)))
                        {
                            clients.Add(client);
                            ClientInsertEvent(client);              //插入客户端
                        }
                        MessageInsertEvent(point.ToString(), imsg); //插入消息

                        if (imsg.Type.Equals("INFO"))
                        {
                            LogRealize.Info($"[{imsg.Time}]{imsg.Message}", imsg.Client);
                        }
                        if (imsg.Type.Equals("WARN"))
                        {
                            LogRealize.Warn($"[{imsg.Time}]{imsg.Message}", imsg.Client);
                        }
                        if (imsg.Type.Equals("ERROR"))
                        {
                            if (imsg.Exception == null)
                            {
                                LogRealize.Error($"[{imsg.Time}]{imsg.Message}", imsg.Client);
                            }
                            else
                            {
                                LogRealize.Error(imsg.Exception, imsg.Client, $"[{imsg.Time}]{imsg.Message}");
                            }
                        }
                        if (imsg.Type.Equals("FATAL"))
                        {
                            if (imsg.Exception == null)
                            {
                                LogRealize.Fatal($"[{imsg.Time}]{imsg.Message}", imsg.Client);
                            }
                            else
                            {
                                LogRealize.Fatal(imsg.Exception, imsg.Client, $"[{imsg.Time}]{imsg.Message}");
                            }
                        }
                        if (imsg.Type.Equals("DEBUG"))
                        {
                            if (imsg.Exception == null)
                            {
                                LogRealize.Debug($"[{imsg.Time}]{imsg.Message}", imsg.Client);
                            }
                            else
                            {
                                LogRealize.Debug(imsg.Exception, imsg.Client, $"[{imsg.Time}]{imsg.Message}");
                            }
                        }
                    }
                }
            }, token);
        }
Exemplo n.º 6
0
        private TransportProvider<EndPoint> AddUdpClient(EndPoint udpClientEndPoint)
        {
            TransportProvider<EndPoint> udpClient = new TransportProvider<EndPoint>();
            IPEndPoint udpClientIPEndPoint = udpClientEndPoint as IPEndPoint;
            UdpClientInfo udpClientInfo;

            // Set up client
            udpClient.SetReceiveBuffer(ReceiveBufferSize);
            udpClient.SetSendBuffer(SendBufferSize);
            udpClient.Provider = udpClientIPEndPoint;

            // If the IP specified for the client is a multicast IP, subscribe to the specified multicast group.
            if ((object)udpClientIPEndPoint != null && Transport.IsMulticastIP(udpClientIPEndPoint.Address))
            {
                SocketOptionLevel level = udpClientIPEndPoint.AddressFamily == AddressFamily.InterNetworkV6 ? SocketOptionLevel.IPv6 : SocketOptionLevel.IP;
                string multicastSource;

                if (m_configData.TryGetValue("multicastSource", out multicastSource))
                {
                    IPAddress sourceAddress = IPAddress.Parse(multicastSource);
                    IPAddress localAddress = (udpClientIPEndPoint.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any);

                    if (sourceAddress.AddressFamily != udpClientIPEndPoint.AddressFamily)
                        throw new InvalidOperationException(string.Format("Source address \"{0}\" is not in the same IP format as server address \"{1}\"", sourceAddress, udpClientIPEndPoint.Address));

                    if (localAddress.AddressFamily != udpClientIPEndPoint.AddressFamily)
                        throw new InvalidOperationException(string.Format("Local address \"{0}\" is not in the same IP format as server address \"{1}\"", localAddress, udpClientIPEndPoint.Address));

                    MemoryStream membershipAddresses = new MemoryStream();

                    byte[] serverAddressBytes = udpClientIPEndPoint.Address.GetAddressBytes();
                    byte[] sourceAddressBytes = sourceAddress.GetAddressBytes();
                    byte[] localAddressBytes = localAddress.GetAddressBytes();

                    membershipAddresses.Write(serverAddressBytes, 0, serverAddressBytes.Length);
                    membershipAddresses.Write(sourceAddressBytes, 0, sourceAddressBytes.Length);
                    membershipAddresses.Write(localAddressBytes, 0, localAddressBytes.Length);

                    udpClient.MulticastMembershipAddresses = membershipAddresses.ToArray();

                    // Execute multicast subscribe for specific source
                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.AddSourceMembership, udpClient.MulticastMembershipAddresses);
                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.MulticastTimeToLive, int.Parse(m_configData["multicastTimeToLive"]));
                }
                else
                {
                    // Execute multicast subscribe for any source
                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.AddMembership, new MulticastOption(udpClientIPEndPoint.Address));
                    m_udpServer.Provider.SetSocketOption(level, SocketOptionName.MulticastTimeToLive, int.Parse(m_configData["multicastTimeToLive"]));
                }
            }

            // Create client info object
            udpClientInfo = new UdpClientInfo()
            {
                Client = udpClient,
                SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(),
                SendLock = new SpinLock(),
                SendQueue = new ConcurrentQueue<UdpServerPayload>()
            };

            // Set up SocketAsyncEventArgs
            udpClientInfo.SendArgs.RemoteEndPoint = udpClient.Provider;
            udpClientInfo.SendArgs.SetBuffer(udpClient.SendBuffer, 0, udpClient.SendBufferSize);
            udpClientInfo.SendArgs.Completed += m_sendHandler;

            // Add new client to the lookup
            m_clientInfoLookup.TryAdd(udpClient.ID, udpClientInfo);
            OnClientConnected(udpClient.ID);

            return udpClient;
        }