本文继续介绍其他的几种进程间通讯方式。
Socket
Socket即套接字,是进程间通讯的一个非常常用的方法。在.NET中,套接字的实现为System.Net.Sockets类,这个类是System.Net命名空间最重要的一个类,该命名空间内的几乎所有其他类都是基于Sockets类实现的。该类支持非常多的协议类型,在创建Socket时即可指定。
客户端:
static async Task Main(string[] args) { int port = 7777; IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); Socket client = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); await client.ConnectAsync(endPoint); var message = "Hello Server"; var messageBytes = Encoding.UTF8.GetBytes(message); await client.SendAsync(messageBytes, SocketFlags.None); var buffer = new byte[1024]; var received = await client.ReceiveAsync(buffer, SocketFlags.None); var response = Encoding.UTF8.GetString(buffer, 0, received); Console.WriteLine(response); Console.ReadLine(); client.Shutdown(SocketShutdown.Both); }
服务端:
static async Task Main(string[] args) { int port = 7777; IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); Socket server = new(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.Bind(endPoint); server.Listen(100); var handler = await server.AcceptAsync(); var buffer = new byte[1024]; var received = await handler.ReceiveAsync(buffer, SocketFlags.None); var response = Encoding.UTF8.GetString(buffer, 0, received); Console.WriteLine(response); var message = "Hello Client"; var messageBytes = Encoding.UTF8.GetBytes(message); await handler.SendAsync(messageBytes, 0); Console.ReadLine(); }
在Sockets类的基础上,.NET还封装了TcpClient、UdpClient、HttpClient等类,这些类可以让你专注于使用特定的协议传输数据,而无需关注连接细节。