在C#中,你可以使用System.Net.Sockets
命名空间中的Socket
类来创建套接字连接
using System;
using System.Net;
using System.Net.Sockets;
class SocketExample
{
static void Main(string[] args)
{
// 创建一个TCP/IP套接字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
// 解析服务器地址
IPAddress serverAddress = IPAddress.Parse("127.0.0.1");
// 创建一个端点(服务器地址和端口)
IPEndPoint endPoint = new IPEndPoint(serverAddress, 8080);
// 连接到服务器
socket.Connect(endPoint);
Console.WriteLine("Connected to server.");
// 发送数据
string message = "Hello, Server!";
byte[] data = Encoding.ASCII.GetBytes(message);
socket.Send(data);
Console.WriteLine("Message sent: " + message);
// 接收数据
byte[] buffer = new byte[1024];
int received = socket.Receive(buffer);
string response = Encoding.ASCII.GetString(buffer, 0, received);
Console.WriteLine("Message received: " + response);
// 关闭套接字
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
这个示例展示了如何创建一个TCP/IP套接字,连接到服务器,发送数据,接收响应,然后关闭套接字。请注意,你需要根据实际情况修改服务器地址和端口。