Mit C# Events kannst du Klassen zu einem bestimmten Zeitpunkt über ein Geschehen in deiner Anwendung benachrichtigen und Daten übersenden.
public class SimpleTCPServer
{
private TcpListener listener;
public SimpleTCPServer()
{
listener = new TcpListener(IPAddress.Any, 1234);
}
public void StartServer()
{
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Thread clientThread = new Thread(HandleClient);
clientThread.Start(client);
OnClientConnect(client);
}
}
static void HandleClient(object obj)
{
TcpClient tcpClient = (TcpClient)obj;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
break;
}
if (bytesRead == 0)
break;
string clientMessage = Encoding.ASCII.GetString(message, 0, bytesRead);
Console.WriteLine($"Received: {clientMessage}");
byte[] response = Encoding.ASCII.GetBytes("Server received your message");
clientStream.Write(response, 0, response.Length);
clientStream.Flush();
}
tcpClient.Close();
}
protected virtual void OnClientConnect(TcpClient client)
{
ClientConnect?.Invoke(client);
}
public event Action<TcpClient> ClientConnect;
}
In der abgeleiteten Klasse kannst du das Event dann überschreiben.
class MyApp
{
SimpleTCPServer srv;
public void Main()
{
srv = new SimpleTCPServer();
srv.ClientConnect += OnClientConnect;
srv.StartServer();
}
public virtual void OnClientConnect(TcpClient client)
{
// ...
}
}