c#socket接收数据传送事件示例
时间: 2024-10-30 19:05:31 浏览: 2
在C#中,Socket编程通常用于网络通信,包括接收和发送数据。这里是一个简单的例子,展示了如何使用TcpClient和MulticastDelegate来监听接收到的数据并触发一个事件:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
public class SocketReceiver
{
public event EventHandler<DataReceivedEventArgs> DataReceived; // 定义事件
private TcpListener listener = new TcpListener(IPAddress.Any, 8080); // 创建监听器
public void StartListening()
{
listener.Start(); // 启动监听
Console.WriteLine("Listening for incoming connections...");
// 当有新连接时,开始接收数据并触发事件
listener.BeginAcceptTcpClient(AcceptCallback, null);
}
private void AcceptCallback(IAsyncResult ar)
{
try
{
TcpClient client = listener.EndAccept(ar); // 接受连接
NetworkStream stream = client.GetStream(); // 获取流
byte[] buffer = new byte[4096]; // 定义缓冲区
int bytesRead = stream.Read(buffer, 0, buffer.Length); // 接收数据
if (bytesRead > 0)
{
string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead); // 解码数据
Console.WriteLine($"Received data: {receivedData}");
// 触发事件,通知所有订阅者数据已接收
DataReceived?.Invoke(this, new DataReceivedEventArgs(receivedData));
}
else
{
Console.WriteLine("Connection closed.");
client.Close();
}
listener.BeginAcceptTcpClient(AcceptCallback, null); // 继续监听新的连接
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
public class DataReceivedEventArgs : EventArgs
{
public string Data { get; set; }
public DataReceivedEventArgs(string data)
{
Data = data;
}
}
// 在主程序中使用事件
class Program
{
static void Main()
{
SocketReceiver receiver = new SocketReceiver();
receiver.DataReceived += OnDataReceived; // 订阅事件
receiver.StartListening();
Console.ReadLine(); // 等待输入以保持控制台窗口打开
}
private static void OnDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine($"Event triggered! Received: {e.Data}");
}
}
```
当你运行这个程序时,它会监听8080端口,并在接收到数据时触发`DataReceived`事件。主程序中的`OnDataReceived`方法会在事件发生时被调用。
阅读全文