在C#中,使用Socket發送數據需要遵循以下步驟:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
TcpClient client = new TcpClient();
await client.ConnectAsync("example.com", 80); // 將"example.com"和端口80替換為目標服務器的地址和端口
NetworkStream stream = client.GetStream();
byte[] dataToSend = Encoding.ASCII.GetBytes("Hello, Server!"); // 將"Hello, Server!"替換為要發送的數據
await stream.WriteAsync(dataToSend, 0, dataToSend.Length);
stream.Close();
client.Close();
這是一個完整的示例,展示了如何使用C# Socket發送數據:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketExample
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
try
{
TcpClient client = new TcpClient();
await client.ConnectAsync("example.com", 80);
NetworkStream stream = client.GetStream();
byte[] dataToSend = Encoding.ASCII.GetBytes("Hello, Server!");
await stream.WriteAsync(dataToSend, 0, dataToSend.Length);
stream.Close();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
請注意,這個示例使用了async/await
語法。如果你不熟悉這種語法,可以查閱有關C#異步編程的文檔。