当前位置: 首页>>代码示例>>C#>>正文


C# Socket.ConnectTaskAsync方法代码示例

本文整理汇总了C#中Socket.ConnectTaskAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.ConnectTaskAsync方法的具体用法?C# Socket.ConnectTaskAsync怎么用?C# Socket.ConnectTaskAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Socket的用法示例。


在下文中一共展示了Socket.ConnectTaskAsync方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Connect

		public async Task Connect(string hostname, int port, Action notifyWhenClosed, int index)
		{
			_index = index;
			var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
			var addresses = Dns.GetHostAddresses(hostname);
			var started = false;

			foreach (var ipAddress in addresses)
			{
				if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
				{
					started = true;
					try
					{
						await socket.ConnectTaskAsync(new IPEndPoint(ipAddress, port));
					}
					catch (Exception)
					{
						socket.Dispose();
						throw;
					}
					break;
				}
			}

			if (!started) throw new Exception("Invalid hostname " + hostname); // ipv6 not supported yet

			WireStreams(socket, notifyWhenClosed);
		}
开发者ID:danielmarbach,项目名称:RabbitMqNext,代码行数:29,代码来源:SocketHolder.cs

示例2: PingServerAsync

        /// <summary>
        /// Pings a minecraft server and returns the result string
        /// </summary>
        /// <param name="remoteAddress">The server adress</param>
        /// <returns>The resulting string</returns>
        public static async Task<string> PingServerAsync(IPEndPoint remoteAddress)
        {
            var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

            await socket.ConnectTaskAsync(remoteAddress);

            using (var networkStream = new NetworkStream(socket))
            {
                var remoteInterface = ServerRemoteInterface.Create(networkStream, 48);

                await remoteInterface.SendPacketAsync(new PlayerListPing { MagicByte = 1 });

                var result = await remoteInterface.ReadPacketAsync();

                var disconnectPacket = result as DisconnectPacket;
                if (disconnectPacket != null)
                    return disconnectPacket.Reason;
                throw new PacketException("Server return invalid packet");
            }
        }
开发者ID:pdelvo,项目名称:Pdelvo.Minecraft.Proxy,代码行数:25,代码来源:MinecraftPinger.cs

示例3: InitializeServerAsync

        /// <summary>
        ///   Asynchronously initialize the server side of this connection
        /// </summary>
        /// <param name="serverEndPoint"> Information of the new server this connection should connect to. </param>
        /// <returns> A task which returns the LogOnPacket or DisconnectPacket of the established connection. </returns>
        public async Task<Packet> InitializeServerAsync(RemoteServerInfo serverEndPoint)
        {
            ProxyEndPoint server = null;
            try
            {
                UnregisterServer ();
                _serverEndPoint = null;

                if (!string.IsNullOrEmpty(serverEndPoint.KickMessage))
                {
                    await KickUserAsync(serverEndPoint.KickMessage);
                    throw new OperationCanceledException("User got kicked.");
                }

                if (serverEndPoint.MinecraftVersion == 0)
                    _server.GetServerVersion(this, serverEndPoint);
                if (serverEndPoint.MinecraftVersion == null)
                {
                    var information =await  MinecraftPinger.GetServerInformationAsync(serverEndPoint.EndPoint);
                    if((serverEndPoint.MinecraftVersion = information.ProtocolVersion) == null)
                        throw new InvalidOperationException("Could not auto detect server version");
                    
                }

                var socket = new Socket(serverEndPoint.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
                                 {
                                     ReceiveBufferSize = 1024*1024
                                 };

                await socket.ConnectTaskAsync(serverEndPoint.EndPoint);
                server =
                    new ProxyEndPoint(
                        ServerRemoteInterface.Create(new NetworkStream(socket), (int)serverEndPoint.MinecraftVersion),
                        (int)serverEndPoint.MinecraftVersion);
                server.RemoteEndPoint = (IPEndPoint) socket.RemoteEndPoint;
                var handshakeRequest = new HandshakeRequest
                                           {
                                               UserName = Username,
                                               Host = Host,
                                               ProtocolVersion = (byte) serverEndPoint.MinecraftVersion
                                           };
                await server.SendPacketAsync(handshakeRequest);

                Packet tp = await server.ReceivePacketAsync ();

                if (tp is DisconnectPacket)
                {
                    throw new OperationCanceledException((tp as DisconnectPacket).Reason);
                }

                var encryptionKeyRequest = tp as EncryptionKeyRequest;

                server.ConnectionKey = ProtocolSecurity.GenerateAes128Key ();
                byte[] key = ProtocolSecurity.RsaEncrypt(server.ConnectionKey, encryptionKeyRequest.PublicKey.ToArray (),
                                                         false);
                byte[] verifyToken = ProtocolSecurity.RsaEncrypt(encryptionKeyRequest.VerifyToken.ToArray (),
                                                                 encryptionKeyRequest.PublicKey.ToArray (), false);

                var encryptionKeyResponse = new EncryptionKeyResponse
                                                {
                                                    SharedKey = key,
                                                    VerifyToken = verifyToken
                                                };
                await server.SendPacketAsync(encryptionKeyResponse);

                Packet p = await server.ReceivePacketAsync ();

                server.EnableAes ();

                await server.SendPacketAsync(new RespawnRequestPacket ());

                return await server.ReceivePacketAsync ();
            }
            catch (Exception ex)
            {
                _quitMessagePosted = true;
                _logger.Error("Could not connect to remote server", ex);
                throw;
            }
            finally
            {
                _serverEndPoint = server;
            }
        }
开发者ID:pdelvo,项目名称:Pdelvo.Minecraft.Proxy,代码行数:89,代码来源:ProxyConnection.cs

示例4: Connect

        private async Task<Connection> Connect()
        {
            triedToConnect = true;

            Match addressMatch = serverAddressRegex.Match(connectionDialog.ServerAddress);
            if (!addressMatch.Success)
                throw new ArgumentException("Invalid server address (must be in form <host>[:<port>])");

            string host = addressMatch.Groups["host"].Value;

            var portGroup = addressMatch.Groups["port"];
            int port = 10000;
            if (portGroup.Success && !int.TryParse(portGroup.Value, out port))
                throw new ArgumentException($"Invalid server port ${portGroup.Value}");

            IPAddress[] hostAddresses = await Dns.GetHostAddressesAsync(host);
            Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            await socket.ConnectTaskAsync(hostAddresses, port);

            return new Connection(socket);
        }
开发者ID:sewa312,项目名称:hpcourse,代码行数:21,代码来源:MainForm.cs

示例5: ConnectAsync

        public Task ConnectAsync(string hostName, int portNumber)
        {
            var hostEntry = new DnsEndPoint(hostName, portNumber);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            return _socket.ConnectTaskAsync(hostEntry);
        }
开发者ID:garaemon,项目名称:RosSharp,代码行数:8,代码来源:TcpRosClient.cs


注:本文中的Socket.ConnectTaskAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。