TcpListener
program.cs
csharp
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace TCPListener
{
internal class Program
{
static async Task Main(string[] args)
{
EchoServerListener listener = new EchoServerListener(28888);
listener.Start();
while (true)
{
}
}
}
}
TCPListener.cs
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace TCPListener
{
class Client
{
public TcpClient TcpClient { get; private set; }
public NetworkStream Stream { get; private set; }
public int BufferSize { get; private set; }
public byte[] Buffer { get; private set; }
public Client(TcpClient tcpClient, NetworkStream stream, int bufferSize = 1024)
{
TcpClient = tcpClient;
Stream = stream;
BufferSize = bufferSize;
Buffer = new byte[BufferSize];
}
}
internal class EchoServerListener
{
private readonly IPEndPoint _IPEndPoint;
private readonly TcpListener _Listener;
private readonly List<Client> _Clients;
public EchoServerListener(int port)
{
_IPEndPoint = new IPEndPoint(IPAddress.Any, port);
_Listener = new TcpListener(_IPEndPoint);
_Clients = new List<Client>();
}
public async void Start()
{
try
{
_Listener.Start();
try
{
while (true)
{
using TcpClient tcpClient = await _Listener.AcceptTcpClientAsync();
await using NetworkStream stream = tcpClient.GetStream();
Client client = new Client(tcpClient, stream);
_Clients.Add(client);
string message = "Who are you?";
Encoding.UTF8.GetBytes(message, 0, message.Length, client.Buffer, 0);
await stream.WriteAsync(client.Buffer, 0, message.Length);
int received = await stream.ReadAsync(client.Buffer);
message = Encoding.UTF8.GetString(client.Buffer, 0, received);
message = $"Hello, {message}!";
Encoding.UTF8.GetBytes(message, 0, message.Length, client.Buffer, 0);
await stream.WriteAsync(client.Buffer, 0, message.Length);
}
}
catch
{
}
}
finally
{
_Listener.Stop();
}
}
public void Stop()
{
_Listener.Stop();
}
}
}
TcpClient
Program.cs
csharp
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace TCPClient
{
internal class Program
{
static async Task Main(string[] args)
{
using TcpClient tcpClient = new TcpClient("localhost", 28888);
await using NetworkStream stream = tcpClient.GetStream();
byte[] buffer = new byte[1024];
int received = await stream.ReadAsync(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, received);
Console.WriteLine($"[Server] \"{message}\"");
message = Console.ReadLine();
byte[] bytes = Encoding.UTF8.GetBytes(message);
await stream.WriteAsync(bytes);
received = await stream.ReadAsync(buffer);
message = Encoding.UTF8.GetString(buffer, 0, received);
Console.WriteLine($"[Server] \"{message}\"");
}
}
}