在C#中,使用Socket编程进行网络通信的基本步骤如下:
using System.Net;
using System.Net.Sockets;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 8080;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
socket.Bind(localEndPoint);
Listen
方法以便监听客户端的连接请求。socket.Listen(10); // 最多允许10个等待连接的客户端
Accept
方法接受客户端的连接请求。这将返回一个新的Socket对象,表示与客户端的连接。Socket clientSocket = socket.Accept();
Send
和Receive
方法在客户端和服务器之间发送和接收数据。// 发送数据
byte[] sendBuffer = Encoding.ASCII.GetBytes("Hello, Server!");
clientSocket.Send(sendBuffer);
// 接收数据
byte[] receiveBuffer = new byte[1024];
int receivedBytes = clientSocket.Receive(receiveBuffer);
string receivedData = Encoding.ASCII.GetString(receiveBuffer, 0, receivedBytes);
Shutdown
和Close
方法关闭Socket连接。clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
socket.Close();
这些基本步骤适用于C#中的Socket编程。根据实际需求,可能需要对这些步骤进行一些调整。