Looking for c# Keywords? Try Ask4Keywords

C# Language Async TCP Client


Использование async/await в приложениях C # упрощает многопоточность. Так вы можете использовать async/await wait в сочетании с TcpClient.

// Declare Variables
string host = "stackoverflow.com";
int port = 9999;
int timeout = 5000;

// Create TCP client and connect
// Then get the netstream and pass it
// To our StreamWriter and StreamReader
using (var client = new TcpClient())
using (var netstream = client.GetStream()) 
using (var writer = new StreamWriter(netstream))
using (var reader = new StreamReader(netstream))
    // Asynchronsly attempt to connect to server
    await client.ConnectAsync(host, port);
    // AutoFlush the StreamWriter
    // so we don't go over the buffer
    writer.AutoFlush = true;
    // Optionally set a timeout
    netstream.ReadTimeout = timeout;

    // Write a message over the TCP Connection
    string message = "Hello World!";
    await writer.WriteLineAsync(message);
    // Read server response
    string response = await reader.ReadLineAsync();
    Console.WriteLine(string.Format($"Server: {response}"));                
// The client and stream will close as control exits
// the using block (Equivilent but safer than calling Close();