Example #1
0
        public Task <bool> ConnectAsync(
            string hostName, ushort port,
            uint channelLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT,
            uint data         = 0)
        {
            if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
            {
                throw new ArgumentOutOfRangeException("channelLimit");
            }

            var tcs     = new TaskCompletionSource <bool>();
            var address = new Address {
                HostName = hostName, Port = port
            };
            ENetAddress nativeAddress = address.Struct;

            this.peerPtr = NativeMethods.EnetHostConnect(
                this.service.HostPtr, ref nativeAddress, channelLimit, data);
            if (this.peerPtr == IntPtr.Zero)
            {
                throw new EException("host connect call failed.");
            }
            this.service.PeersManager.Add(this.peerPtr, this);
            this.Connected = eEvent =>
            {
                if (eEvent.EventState == EventState.DISCONNECTED)
                {
                    tcs.TrySetException(new EException("socket disconnected in connect"));
                }
                tcs.TrySetResult(true);
            };
            return(tcs.Task);
        }