winform 使用异步的方式socket创建tcpip服务端
时间: 2023-07-30 09:07:30 浏览: 50
首先,创建 Winform 应用程序,然后在项目中添加 `System.Net.Sockets` 引用。
接下来,在 Winform 窗体中添加一个按钮和一个文本框,用于显示客户端连接和通信的信息。
然后,在按钮的 Click 事件中添加以下代码:
```csharp
private async void btnStart_Click(object sender, EventArgs e)
{
// 创建一个 TcpListener 对象,并绑定到本地 IP 地址和端口号
TcpListener listener = new TcpListener(IPAddress.Any, 8888);
// 开始监听客户端连接请求
listener.Start();
// 显示服务器已启动
txtLog.AppendText("服务器已启动,等待客户端连接...\r\n");
while (true)
{
try
{
// 等待客户端连接请求,异步方式
TcpClient client = await listener.AcceptTcpClientAsync();
// 客户端已连接,显示客户端 IP 地址和端口号
txtLog.AppendText($"客户端已连接,IP 地址:{((IPEndPoint)client.Client.RemoteEndPoint).Address},端口号:{((IPEndPoint)client.Client.RemoteEndPoint).Port}\r\n");
// 处理客户端请求,异步方式
Task.Factory.StartNew(() => HandleClient(client));
}
catch (Exception ex)
{
// 显示异常信息
txtLog.AppendText($"发生异常:{ex.Message}\r\n");
}
}
}
private void HandleClient(TcpClient client)
{
// 获取客户端网络流
NetworkStream stream = client.GetStream();
// 定义接收缓冲区
byte[] buffer = new byte[1024];
while (true)
{
try
{
// 读取客户端发送的数据,异步方式
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
// 显示客户端发送的消息
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
txtLog.AppendText($"收到客户端消息:{message}\r\n");
// 将消息转发给所有客户端
BroadcastMessage(message, client);
}
else
{
// 客户端已断开连接
txtLog.AppendText($"客户端已断开连接,IP 地址:{((IPEndPoint)client.Client.RemoteEndPoint).Address},端口号:{((IPEndPoint)client.Client.RemoteEndPoint).Port}\r\n");
// 关闭网络流和客户端连接
stream.Close();
client.Close();
break;
}
}
catch (Exception ex)
{
// 显示异常信息
txtLog.AppendText($"发生异常:{ex.Message}\r\n");
}
}
}
private void BroadcastMessage(string message, TcpClient excludeClient)
{
// 将消息转换为字节数组
byte[] buffer = Encoding.UTF8.GetBytes(message);
// 遍历所有客户端,将消息转发给除 excludeClient 以外的所有客户端
foreach (TcpClient client in clients)
{
if (client != excludeClient)
{
try
{
NetworkStream stream = client.GetStream();
stream.Write(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
// 显示异常信息
txtLog.AppendText($"发生异常:{ex.Message}\r\n");
}
}
}
}
```
以上代码中,`btnStart_Click` 方法启动 TCP/IP 服务端,并在循环中等待客户端连接请求。当客户端连接成功后,会调用 `HandleClient` 方法处理客户端请求,并将处理过程放在一个新的线程中执行。在 `HandleClient` 方法中,使用异步方式读取客户端发送的数据,并在接收到消息后将消息转发给除当前客户端以外的所有客户端。
注意:以上代码仅供参考,实际使用时需要根据需求进行修改和完善。