帮我用C#写一个异步带委托的复杂TCP Server通信接口
以下是一个简单的异步带委托的复杂TCP Server通信接口的示例代码:
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading;
namespace TcpServerExample { class Program { static void Main(string[] args) { StartServer(); Console.ReadKey(); }
static void StartServer()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8080);
listener.Start();
Console.WriteLine("Server started.");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Client connected.");
Thread thread = new Thread(() => HandleClient(client));
thread.Start();
}
}
static void HandleClient(TcpClient client)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
// Read client data asynchronously
AsyncCallback callback = new AsyncCallback(ReadCallback);
IAsyncResult result = stream.BeginRead(buffer, 0, buffer.Length, callback, null);
bytesRead = stream.EndRead(result);
}
catch
{
// Error occurred while reading client data
break;
}
if (bytesRead == 0)
{
// Client disconnected
break;
}
// Convert client data to string
string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received data from client: " + data);
// Process client data asynchronously
AsyncCallback callback2 = new AsyncCallback(ProcessCallback);
IAsyncResult result2 = callback2.BeginInvoke(data, null, null);
}
client.Close();
Console.WriteLine("Client disconnected.");
}
static void ReadCallback(IAsyncResult result)
{
// Do nothing
}
static void ProcessCallback(string data)
{
// Process client data here
Console.WriteLine("Processing data: " + data);
}
}
原文地址: https://www.cveoy.top/t/topic/eGcg 著作权归作者所有。请勿转载和采集!