-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
50 lines (41 loc) · 1.25 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// ReSharper disable LocalizableElement
void OnDataReceived(
byte[] data)
{
Console.WriteLine($"Received Data Length: {data.Length}");
var dataStr = Encoding.ASCII
.GetString(data)
.RemoveNonPrintableCharacter();
Console.WriteLine($"Received Data: {dataStr}");
}
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddConsole();
});
var logger = loggerFactory.CreateLogger<TcpClient>();
var tcpClient = new TcpClient(
logger,
"tcpbin.com",
4242,
new TcpClientConfig
{
TerminationType = TerminationType.LineFeed,
ConnectTimeout = 1000,
});
tcpClient.Connected += () => Console.WriteLine("Connected");
tcpClient.Disconnected += () => Console.WriteLine("Disconnected");
tcpClient.ConnectionStateChanged += (_, args) => Console.WriteLine($"Connection: {args.State}");
tcpClient.DataReceived += OnDataReceived;
if (!await tcpClient.Connect())
{
Console.WriteLine("Cannot connect");
tcpClient.Dispose();
return;
}
await tcpClient.Send("ping", CancellationToken.None);
await Task.Delay(TimeSpan.FromMilliseconds(400));
await tcpClient.Disconnect();
tcpClient.Dispose();
Console.WriteLine("Press any key for quit");
Console.ReadLine();