예제 #1
0
        public async void StartClient(string host, int port)
        {
            Uri gameServerUri = new Uri(host);

            IPHostEntry hostEntry = Dns.GetHostEntry(gameServerUri.Host);

            if (hostEntry.AddressList.Length == 0)
            {
                throw new Exception("Unable to resolve host: " + gameServerUri.Host);
            }
            var endpoint = hostEntry.AddressList[0];

            try
            {
                this.listener = new System.Net.Sockets.Socket(endpoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                this.listener.BeginConnect(endpoint, port, this.OnConnectCallback, this.listener);
                //this.connected.WaitOne();
                RemoteAddress = (IPEndPoint)this.listener.RemoteEndPoint;
                LocalAddress  = (IPEndPoint)this.listener.LocalEndPoint;

                mKCP = new KCP((uint)(new Random().Next(1, Int32.MaxValue)), Send);
                // normal:  0, 40, 2, 1
                // fast:    0, 30, 2, 1
                // fast2:   1, 20, 2, 1
                // fast3:   1, 10, 2, 1
                mKCP.NoDelay(1, 10, 2, 1);
                mKCP.WndSize(128, 128);
                mKCP.SetStreamMode(true);
                mRecvBuffer.Clear();

                _tokenSourceReceiver = new CancellationTokenSource();


                await Receive();

                var connectedHandler = this.Connected;

                if (connectedHandler != null)
                {
                    connectedHandler(this);
                }
            }
            catch (Exception ex)//SocketException
            {
                await CloseAsync();

                OnError(ex.ToString());
            }
        }