2024-12-14 15:17:58 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace Client;
|
|
|
|
|
|
|
|
|
|
public class Program
|
|
|
|
|
{
|
|
|
|
|
static void Main(string[] args)
|
|
|
|
|
{
|
|
|
|
|
using TcpClient client = new("127.0.0.1", 12345);
|
|
|
|
|
|
|
|
|
|
byte[] toSend = Encoding.ASCII.GetBytes("hello server");
|
|
|
|
|
|
|
|
|
|
var stream = client.GetStream();
|
|
|
|
|
|
|
|
|
|
var inputTask = Task.Run(async () => await HandleUserInput(client, stream));
|
|
|
|
|
var serverInput = Task.Run(async () => await HandleServerInput(client, stream));
|
|
|
|
|
|
|
|
|
|
_ = Task.WaitAny(inputTask, serverInput);
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static async Task HandleUserInput(TcpClient client, NetworkStream stream) {
|
|
|
|
|
while(client.Connected) {
|
|
|
|
|
string? input = Console.ReadLine();
|
|
|
|
|
if(input == null) {
|
|
|
|
|
await Task.Delay(100);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
else {
|
|
|
|
|
stream.Write(Encoding.ASCII.GetBytes(input));
|
|
|
|
|
Console.WriteLine($"[{DateTime.Now}]Sent to server: {input}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static async Task HandleServerInput(TcpClient client, NetworkStream stream) {
|
|
|
|
|
byte[] buffer = new byte[1024];
|
|
|
|
|
while(client.Connected) {
|
|
|
|
|
int readLen = await stream.ReadAsync(buffer);
|
|
|
|
|
if(readLen != 0) {
|
|
|
|
|
string fromServer = Encoding.ASCII.GetString(buffer[..readLen]);
|
|
|
|
|
Console.WriteLine($"[{DateTime.Now}]\t\tFrom server: {fromServer}");
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|