在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连接。