在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編程。根據實際需求,可能需要對這些步驟進行一些調整。