C#是一种基于对象的程序设计语言,可以使用它来实现Socket数据接收。在C#中,Socket可以通过三种方式进行数据接收,分别是:同步方式、异步方式和事件驱动方式。
- 同步方式
同步方式是一种阻塞式的接收方式,即程序执行在接收Socket数据的阶段会一直阻塞,直到数据接收完成后程序才会继续执行。
代码示例:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketReceiver
{
public static void Main()
{
// 创建Socket对象
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定IP地址和端口号
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
listener.Bind(localEndPoint);
// 开始监听连接请求
listener.Listen(10);
Socket handler = listener.Accept();
// 接收数据
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
Console.WriteLine("接收到的消息: {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
// 关闭Socket
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
- 异步方式
异步方式是一种非阻塞式的接收方式,即程序执行在接收Socket数据的阶段不会一直阻塞,而是可以继续执行其他任务,当数据接收完成后再处理接收到的数据。
代码示例:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class SocketReceiver
{
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
public static void Main()
{
// 创建Socket对象
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定IP地址和端口号
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
listener.Bind(localEndPoint);
// 开始监听连接请求
listener.Listen(10);
while (true)
{
receiveDone.Reset();
Console.WriteLine("等待连接...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
receiveDone.WaitOne();
}
}
public static void AcceptCallback(IAsyncResult ar)
{
receiveDone.Set();
// 获取监听Socket对象
Socket listener = (Socket)ar.AsyncState;
// 创建连接
Socket handler = listener.EndAccept(ar);
// 开始异步接收数据
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
public static void ReceiveCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// 结束异步接收数据
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.sb.Length > 1)
{
string content = state.sb.ToString();
Console.WriteLine("接收到的消息: {0}", content);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
}
- 事件驱动方式
事件驱动方式也是一种非阻塞式的接收方式,与异步方式类似。事件驱动方式是基于事件的编程模型,程序通过订阅Socket的事件来进行数据接收和处理。
代码示例:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketReceiver
{
private static byte[] buffer = new byte[1024];
private static Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public static void Main()
{
// 绑定IP地址和端口号
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
listener.Bind(localEndPoint);
// 开始监听连接请求
listener.Listen(10);
Console.WriteLine("等待连接...");
Socket handler = listener.Accept();
// 订阅数据接收事件
handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), handler);
}
private static void ReceiveCallback(IAsyncResult ar)
{
Socket handler = (Socket)ar.AsyncState;
// 结束异步接收数据
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
Console.WriteLine("接收到的消息: {0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), handler);
}
else
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C# 三种方式实现Socket数据接收 - Python技术站