在C#中進行網絡通信可以使用Socket類來實現,以下是一個使用Socket類進行網絡通信的示例代碼:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Client
{
public static void Main()
{
try
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 8888;
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the server
clientSocket.Connect(ipAddress, port);
// Send data to the server
string data = "Hello from client";
byte[] bytes = Encoding.ASCII.GetBytes(data);
clientSocket.Send(bytes);
// Receive data from the server
byte[] buffer = new byte[1024];
int bytesRead = clientSocket.Receive(buffer);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Server response: " + response);
// Close the socket
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
以上示例代碼展示了一個簡單的客戶端程序,通過Socket類實現了與服務器端的網絡通信。首先創建一個Socket對象并連接到服務器端的IP地址和端口,然后發送數據到服務器端,并接收服務器端返回的數據。最后關閉Socket連接。