Beispiel #1
0
        protected override void onCompleteReadFromServerStream(IAsyncResult iar)
        {
            UdpClient tcpc;

            try
            {
                tcpc = (UdpClient)iar.AsyncState;
                //取得這次傳入資料的長度
                IPEndPoint iPEndPoint   = null;
                byte[]     receiveBytes = tcpc.EndReceive(iar, ref iPEndPoint);

                udpMaintainConnecting = true;
                fireCompleteReadFromServerStream(receiveBytes);
            }
            catch (Exception exc)
            {
                if (!exc.Message.Contains(SocketErrorMsgs) && !exc.Message.Contains(SocketErrorMsgs2))
                {
                    LogProxy.WriteLine(exc.Message);
                }
            }
            finally
            {
                if (udpClient != null && udpClient.Client.Connected)
                {
                    udpClient.BeginReceive(onCompleteReadFromServerStream, udpClient);
                }
            }
        }
Beispiel #2
0
 public override void Connect(IPAddress address, int port)
 {
     tcpClient = new TcpClient(AddressFamily.InterNetworkV6);
     tcpClient.Client.DualMode = true;
     if (!IPTool.IOSCheck(address, out address))
     {
         address = address.MapToIPv6();
     }
     try
     {
         tcpClient.Connect(address, port);
         if (tcpClient.Connected)
         {
             fireCompleteConnect();
             StartReceiveAsync(tcpClient);
         }
         else
         {
             fireCompleteDisconnect();
         }
     }
     catch (SocketException e)
     {
         switch (e.ErrorCode)
         {
         case (int)SocketError.ConnectionRefused:
             fireCompleteDisconnect();
             LogProxy.WriteLine(e.Message);
             break;
         }
     }
 }
Beispiel #3
0
        public RUdp() : base(NetworkProtocol.RUDP)
        {
            listener = new EventBasedNetListener();
            client   = new NetManager(listener)
            {
                DisconnectTimeout = 20 * 1000
            };
            client.UpdateTime = 15;

            listener.PeerConnectedEvent += (NetPeer peer) =>
            {
                LogProxy.WriteLine("Connect Success : " + peer.EndPoint);
                this.peer = peer;
                fireCompleteConnect();
            };

            listener.PeerDisconnectedEvent += (NetPeer peer, DisconnectInfo disconnectInfo) =>
            {
                client.Flush();
                client.Stop();
                fireCompleteDisconnect();
            };

            listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) =>
            {
                byte[] packet = new byte[dataReader.AvailableBytes];
                dataReader.GetBytes(packet, dataReader.AvailableBytes);
                fireCompleteReadFromServerStream(packet);
                dataReader.Recycle();
            };
        }
Beispiel #4
0
        private async Task StartReceiveAsync(TcpClient tcpc)
        {
            Task.Run(async() => {
                while (true)
                {
                    try
                    {
                        byte[] buff = new byte[BufferSize];
                        int count   = await tcpClient.GetStream().ReadAsync(buff, 0, buff.Length);

                        Array.Resize(ref buff, count);
                        if (count.Equals(0))
                        {
                            LogProxy.WriteLine("Get Packet Length = 0");
                            DisConnect();
                            break;
                        }
                        Task.Run(() => { try { fireCompleteReadFromServerStream(buff); } catch (Exception e) { LogProxy.WriteError(e.Message); } });
                    }
                    catch (Exception e)
                    {
                        if (!callForTcpClientClose)
                        {
                            DisConnect();
                        }
                        callForTcpClientClose = false;
                        LogProxy.WriteLine(e.Message);
                        break;
                    }
                }
            });
        }
Beispiel #5
0
 public override void BeginSend(byte[] datagram, int bytes)
 {
     if (udpClient != null)
     {
         udpClient.BeginSend(datagram, bytes, serverIPEndPoint, iar =>
         {
             try
             {
                 UdpClient tcpc;
                 tcpc = (UdpClient)iar.AsyncState;
                 tcpc.EndSend(iar);
             }
             catch (SocketException socketException)
             {
                 if (!socketException.Message.Contains(SocketErrorMsgs3))
                 {
                     LogProxy.WriteLine("Begin Send Socket Error : " + socketException.Message);
                 }
                 else
                 {
                     DisConnect();
                 }
             }
             fireCompleteSend();
         }, udpClient);
     }
 }
Beispiel #6
0
        protected override Task StartServer(CancellationToken cancel)
        {
            // Kick off the actual processing to a new thread and return a Task for the processing thread.
            return(Task.Run(async delegate
            {
                while (true)
                {
                    // We schedule approximately at the configured interval. There may be some small accumulation for the
                    // part of the loop we do not measure but it is close enough to be acceptable for all practical scenarios.
                    var duration = Stopwatch.StartNew();
                    try
                    {
                        using (var stream = new MemoryStream())
                        {
                            var serializer = new TextSerializer(stream);

                            // Do not pass CT because we only want to cancel after pushing, so a flush is always performed.
                            await _registry.CollectAndSerializeAsync(serializer, default);

                            stream.Position = 0;
                            // StreamContent takes ownership of the stream.
                            var response = await _httpClient.PostAsync(_targetUrl, new StreamContent(stream));

                            // If anything goes wrong, we want to get at least an entry in the trace log.
                            response.EnsureSuccessStatusCode();
                        }
                    }
                    catch (ScrapeFailedException ex)
                    {
                        LogProxy.WriteLine($"Skipping metrics push due to failed scrape: {ex.Message}");
                    }
                    catch (Exception ex) when(!(ex is OperationCanceledException))
                    {
                        LogProxy.WriteLine(string.Format("Error in MetricPusher: {0}", ex));
                    }

                    // We stop only after pushing metrics, to ensure that the latest state is flushed when told to stop.
                    if (cancel.IsCancellationRequested)
                    {
                        break;
                    }
                    var sleepTime = _pushInterval - duration.Elapsed;

                    // Sleep until the interval elapses or the pusher is asked to shut down.
                    if (sleepTime > TimeSpan.Zero)
                    {
                        try
                        {
                            await Task.Delay(sleepTime, cancel);
                        }
                        catch (OperationCanceledException)
                        {
                            // The task was cancelled.
                            // We continue the loop here to ensure final state gets pushed.
                            continue;
                        }
                    }
                }
            }));
 // Update is called once per frame
 void Update()
 {
     if (Input.anyKeyDown)
     {
         LogProxy.WriteLine(ProcessedJobCount.WithLabels("android1").Value);
         ProcessedJobCount.WithLabels("android1").Inc();
     }
 }
        public override void ServerCallback(Dictionary <byte, object> server_packet)
        {
            LogProxy.WriteLine("Dictionary Count = " + server_packet.Count + ", first : " + server_packet[0].ToString());
            byte switchCode = byte.Parse(server_packet[0].ToString());

            switch (switchCode)
            {
            case 5:     //接收世界狀態
                Receive_WorldState(server_packet);
                break;
            }
        }
Beispiel #9
0
        internal async Task ResolveEndPointsAsync(ConnectionMultiplexer multiplexer, LogProxy log)
        {
            var cache = new Dictionary <string, IPAddress>(StringComparer.OrdinalIgnoreCase);

            for (int i = 0; i < EndPoints.Count; i++)
            {
                if (EndPoints[i] is DnsEndPoint dns)
                {
                    try
                    {
                        if (dns.Host == ".")
                        {
                            EndPoints[i] = new IPEndPoint(IPAddress.Loopback, dns.Port);
                        }
                        else if (cache.TryGetValue(dns.Host, out IPAddress ip))
                        { // use cache
                            EndPoints[i] = new IPEndPoint(ip, dns.Port);
                        }
                        else
                        {
                            log?.WriteLine($"Using DNS to resolve '{dns.Host}'...");
                            var ips = await Dns.GetHostAddressesAsync(dns.Host).ObserveErrors().ForAwait();

                            if (ips.Length == 1)
                            {
                                ip = ips[0];
                                log?.WriteLine($"'{dns.Host}' => {ip}");
                                cache[dns.Host] = ip;
                                EndPoints[i]    = new IPEndPoint(ip, dns.Port);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        multiplexer.OnInternalError(ex);
                        log?.WriteLine(ex.Message);
                    }
                }
            }
        }
 // Start is called before the first frame update
 void Start()
 {
     LogProxy.WriteLine("start 1");
     pusher = new MetricPusher(endpoint: "http://192.168.2.5:9091/metrics", job: "deviced1", intervalMilliseconds: 5000);
     pusher.Start();
     LogProxy.WriteLine("start 2");
     ProcessedJobCount = Metrics
                         .CreateCounter("myapp_jobs_processed_total", "Number of processed jobs.",
                                        new CounterConfiguration
     {
         // Here you specify only the names of the labels.
         LabelNames = new[] { "DeviceId" }
     });
     ProcessedJobCount.Labels("android1");
 }
        /// <summary>
        /// Awaitable state seeing if this endpoint is connected.
        /// </summary>
        public Task <string> OnConnectedAsync(LogProxy log = null, bool sendTracerIfConnected = false, bool autoConfigureIfConnected = false)
        {
            async Task <string> IfConnectedAsync(LogProxy log, bool sendTracerIfConnected, bool autoConfigureIfConnected)
            {
                log?.WriteLine($"{Format.ToString(this)}: OnConnectedAsync already connected start");
                if (autoConfigureIfConnected)
                {
                    await AutoConfigureAsync(null, log).ForAwait();
                }
                if (sendTracerIfConnected)
                {
                    await SendTracerAsync(log).ForAwait();
                }
                log?.WriteLine($"{Format.ToString(this)}: OnConnectedAsync already connected end");
                return("Already connected");
            }

            if (!IsConnected)
            {
                log?.WriteLine($"{Format.ToString(this)}: OnConnectedAsync init (State={interactive?.ConnectionState})");
                var tcs = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously);
                _ = tcs.Task.ContinueWith(t => log?.WriteLine($"{Format.ToString(this)}: OnConnectedAsync completed ({t.Result})"));
                lock (_pendingConnectionMonitors)
                {
                    _pendingConnectionMonitors.Add(tcs);
                    // In case we complete in a race above, before attaching
                    if (IsConnected)
                    {
                        tcs.TrySetResult("Connection race");
                        _pendingConnectionMonitors.Remove(tcs);
                    }
                }
                return(tcs.Task);
            }
            return(IfConnectedAsync(log, sendTracerIfConnected, autoConfigureIfConnected));
        }
Beispiel #12
0
        /// <summary>
        /// </summary>
        /// <param name="serverIP"></param>
        /// <param name="absoluteFolderPath"> AssetBundle 所在資料夾的絕對路徑。 Ex : D:/Slither/AssetBundle/Android </param>
        private static void upload(string serverIP, string absoluteFolderPath)
        {
            LogProxy.WriteLine($"Upload file to FileServer. IP:{serverIP}, Path:{absoluteFolderPath}");

            var directory = new DirectoryInfo(absoluteFolderPath);

            //查找所有文件並上傳
            foreach (FileInfo file in directory.GetFiles())
            {
                using (WebClient client = new WebClient())
                {
                    var address = $"{serverIP}?FolderName={directory.Name}";
                    client.UploadFile(address, file.FullName);
                }
            }
        }
Beispiel #13
0
 public override void BeginSend(byte[] datagram, int bytes)
 {
     if (tcpClient.Connected)
     {
         try
         {
             tcpClient.GetStream().Write(datagram, 0, bytes);
             fireCompleteSend();
         }
         catch (Exception e)
         {
             LogProxy.WriteLine(e.Message);
             // tell tcpclient don't do tcpClient.GetStream().Read
             tcpClient.GetStream().Flush();
         }
     }
 }
Beispiel #14
0
 /// <summary>
 /// 連線到伺服器
 /// </summary>
 public void ConnectToServer()
 {
     if (this.timer.Enabled)
     {
         if (time > TimeSpan.FromSeconds(ConnectToServerLimit).TotalMilliseconds)
         {
             this.timer.Stop();
             this.time = 0;
         }
         return; //如果正在計時,則跳出
     }
     this.timer.Start();
     if (!IsConnect)
     {
         LogProxy.WriteLine("ConnectToServer");
         gameService.ConnectToServer();
     }
 }
Beispiel #15
0
        public override void Connect(Uri uri)
        {
            SetFireDisconnectTrigger();
            IPAddress addr = IPAddress.Parse(uri.Host);

            if (Application.platform != RuntimePlatform.WebGLPlayer)
            {
                if (IPTool.IOSCheck(addr, out addr))
                {
                    string ipv6UriString = string.Format("ws://[{0}]:{1}/WebSocket", addr.ToString(), uri.Port);
                    uri = new Uri(ipv6UriString);
                }
            }

            mWebSocket = new WebSocket(uri);

            mWebSocket.StartPingThread = true;
            mWebSocket.OnOpen         += webSocket =>
            {
                LogProxy.WriteLine("WebSocket isOpen= " + webSocket.IsOpen);
                if (webSocket.IsOpen)
                {
                    onCompleteConnect(null);
                }
            };
            mWebSocket.OnBinary += (webSocket, message) =>
            {
                fireCompleteReadFromServerStream(message);
            };
            mWebSocket.OnError += (WebSocket webSocket, Exception ex) =>
            {
                LogProxy.WriteLine("OnError");
                webSocket.Close();
                CheckAndFireDisconnect();
                //Debug.LogError(ex.Message);
            };
            mWebSocket.OnClosed += (webSocket, code, message) =>
            {
                LogProxy.WriteLine("OnClose");
                CheckAndFireDisconnect();
            };
            mWebSocket.Open();
        }
Beispiel #16
0
 /// <summary>
 /// 連線到伺服器。連線到伺服器時, isConnect == true
 /// </summary>
 /// <returns>是否執行成功</returns>
 public bool ConnectToServer()
 {
     try
     {
         if (Network.NetworkProtocol != NetworkProtocol.WebSocket)
         {
             IPAddress ipa = null;
             int       nPort;
             string    ip   = "";
             string    port = "";
             string[]  s    = Address.Split(new Char[] { ':' });
             ip   = s[0];
             port = s[1];
             if (string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(port))
             {
                 return(false);
             }
             if (!IPAddress.TryParse(ip, out ipa))
             {
                 LogProxy.WriteLine("Please supply an IP Address.");
                 return(false);
             }
             if (!int.TryParse(port, out nPort))
             {
                 nPort = 23000;
             }
             Network.Connect(ipa, nPort);
         }
         else
         {
             Uri uri = new Uri(Address);
             Network.Connect(uri);
         }
         return(true);
     }
     catch (Exception exc)
     {
         LogProxy.WriteError(exc.Message);
         return(false);
     }
 }
Beispiel #17
0
        public override void Connect(IPAddress addr, int port)
        {
            LogProxy.WriteLine("<color=darkblue>Udp.Connect=>addr=" + addr + ",port=" + port + "</color>");

            if ((maintainConnecting == null) || !maintainConnecting.Enabled)
            {
                udpClient = new UdpClient(AddressFamily.InterNetworkV6);
                Socket newSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)
                {
                    DualMode = true
                };
                udpClient.Client = newSocket;

                if (!IPTool.IOSCheck(addr, out addr))
                {
                    addr = addr.MapToIPv6();
                }
                serverIPEndPoint = new IPEndPoint(addr.MapToIPv6(), port);

                udpClient.Send(ReqConnect, ReqConnect.Length, serverIPEndPoint);
                udpClient.BeginReceive(onCompleteConnect, udpClient);
            }
        }