本文整理汇总了C#中System.Net.Sockets.TcpClient.ConnectAsync方法的典型用法代码示例。如果您正苦于以下问题:C# System.Net.Sockets.TcpClient.ConnectAsync方法的具体用法?C# System.Net.Sockets.TcpClient.ConnectAsync怎么用?C# System.Net.Sockets.TcpClient.ConnectAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.TcpClient
的用法示例。
在下文中一共展示了System.Net.Sockets.TcpClient.ConnectAsync方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateAsync
public static async Task<OpcWriter> CreateAsync(string host, int port = DefaultPort)
{
var client = new System.Net.Sockets.TcpClient();
await client.ConnectAsync(host, port).ConfigureAwait(false);
var stream = client.GetStream();
return new OpcWriter(stream, true);
}
示例2: PingHost
private async Task<bool> PingHost(IPEndPoint target, Guid remote_session_id, CancellationToken cancel_token)
{
Logger.Debug("Ping requested. Try to ping: {0}({1})", target, remote_session_id);
bool result = false;
try {
var client = new System.Net.Sockets.TcpClient();
client.ReceiveTimeout = 2000;
client.SendTimeout = 2000;
await client.ConnectAsync(target.Address, target.Port);
var stream = client.GetStream();
await stream.WriteAsync(new Atom(Atom.PCP_CONNECT, 1), cancel_token);
var helo = new AtomCollection();
helo.SetHeloSessionID(PeerCast.SessionID);
await stream.WriteAsync(new Atom(Atom.PCP_HELO, helo), cancel_token);
var res = await stream.ReadAtomAsync(cancel_token);
if (res.Name==Atom.PCP_OLEH) {
var session_id = res.Children.GetHeloSessionID();
if (session_id.HasValue && session_id.Value==remote_session_id) {
Logger.Debug("Ping succeeded");
result = true;
}
else {
Logger.Debug("Ping failed. Remote SessionID mismatched");
}
}
await stream.WriteAsync(new Atom(Atom.PCP_QUIT, Atom.PCP_ERROR_QUIT), cancel_token);
stream.Close();
client.Close();
}
catch (InvalidDataException e) {
Logger.Debug("Ping failed");
Logger.Debug(e);
}
catch (System.Net.Sockets.SocketException e) {
Logger.Debug("Ping failed");
Logger.Debug(e);
}
catch (EndOfStreamException e) {
Logger.Debug("Ping failed");
Logger.Debug(e);
}
catch (System.IO.IOException io_error) {
Logger.Debug("Ping failed");
Logger.Debug(io_error);
if (!(io_error.InnerException is System.Net.Sockets.SocketException)) {
throw;
}
}
return result;
}
示例3: StartAsync
public async void StartAsync()
{
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString);
if (objSck != null)
{
objSck.Close();
objSck = null;
}
objSck = new System.Net.Sockets.TcpClient();
// 小さいバッファを貯めない(遅延させない)
objSck.NoDelay = true;
try
{
await objSck.ConnectAsync(ipAdd, port);
}
catch (Exception)
{
//return false;
return;
}
//NetworkStreamを取得
ns = objSck.GetStream();
ConnectResult = true;
//return ConnectResult;
}
示例4: Connect
public bool Connect(string host, int port, string module, bool requirewrite = false)
{
if (port == -1)
port = VersionrDefaultPort;
IEnumerator<SharedNetwork.Protocol> protocols = SharedNetwork.AllowedProtocols.Cast<SharedNetwork.Protocol>().GetEnumerator();
Retry:
if (!protocols.MoveNext())
{
Printer.PrintMessage("#e#No valid protocols available.##");
return false;
}
Host = host;
Port = port;
Module = module;
Connected = false;
try
{
Connection = new System.Net.Sockets.TcpClient();
var connectionTask = Connection.ConnectAsync(Host, Port);
if (!connectionTask.Wait(5000))
{
throw new Exception(string.Format("Couldn't connect to target: {0}", this.VersionrURL));
}
}
catch (Exception e)
{
Printer.PrintError(e.Message);
return false;
}
if (Connection.Connected)
{
try
{
Printer.PrintDiagnostics("Connected to server at {0}:{1}", host, port);
Handshake hs = Handshake.Create(protocols.Current);
hs.RequestedModule = Module;
Printer.PrintDiagnostics("Sending handshake...");
Connection.NoDelay = true;
ProtoBuf.Serializer.SerializeWithLengthPrefix<Handshake>(Connection.GetStream(), hs, ProtoBuf.PrefixStyle.Fixed32);
var startTransaction = ProtoBuf.Serializer.DeserializeWithLengthPrefix<Network.StartTransaction>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
if (startTransaction == null || !startTransaction.Accepted)
{
Printer.PrintError("#b#Server rejected connection.##");
if (startTransaction != null && hs.VersionrProtocol != startTransaction.ServerHandshake.VersionrProtocol)
Printer.PrintError("## Protocol mismatch - local: {0}, remote: {1}", hs.VersionrProtocol, startTransaction.ServerHandshake.VersionrProtocol);
else
{
if (startTransaction == null)
Printer.PrintError("## Connection terminated unexpectedly.");
else
Printer.PrintError("## Rejected request.");
return false;
}
Printer.PrintError("#b#Attempting to retry with a lower protocol.##");
goto Retry;
}
Printer.PrintDiagnostics("Server domain: {0}", startTransaction.Domain);
if (Workspace != null && !string.IsNullOrEmpty(startTransaction.Domain) && startTransaction.Domain != Workspace.Domain.ToString())
{
Printer.PrintError("Server domain doesn't match client domain. Disconnecting.");
return false;
}
RemoteDomain = startTransaction.Domain;
if (SharedNetwork.SupportsAuthentication(startTransaction.ServerHandshake.CheckProtocol().Value))
{
var command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
if (command.Type == NetCommandType.Authenticate)
{
bool runauth = true;
var challenge = ProtoBuf.Serializer.DeserializeWithLengthPrefix<AuthenticationChallenge>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
if ((!requirewrite && (command.Identifier & 1) != 0) ||
(requirewrite && (command.Identifier & 2) != 0)) // server supports unauthenticated access
{
AuthenticationResponse response = new AuthenticationResponse()
{
IdentifierToken = string.Empty,
Mode = AuthenticationMode.Guest
};
ProtoBuf.Serializer.SerializeWithLengthPrefix(Connection.GetStream(), response, ProtoBuf.PrefixStyle.Fixed32);
command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
if (command.Type == NetCommandType.Acknowledge)
runauth = false;
}
if (runauth)
{
bool q = Printer.Quiet;
Printer.Quiet = false;
Printer.PrintMessage("Server at #b#{0}## requires authentication.", VersionrURL);
while (true)
{
if (challenge.AvailableModes.Contains(AuthenticationMode.Simple))
{
System.Console.CursorVisible = true;
Printer.PrintMessageSingleLine("#b#Username:## ");
string user = System.Console.ReadLine();
Printer.PrintMessageSingleLine("#b#Password:## ");
string pass = GetPassword();
//.........这里部分代码省略.........