在C#中,使用TcpClient類可以實現客戶端與服務器之間的通信
using System;
using System.IO;
using System.Net.Sockets;
public static TcpClient ConnectToServer(string serverAddress, int port)
{
TcpClient client = new TcpClient();
try
{
client.Connect(serverAddress, port);
Console.WriteLine("Connected to server.");
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to server: {ex.Message}");
client = null;
}
return client;
}
public static void SendAndReceiveData(TcpClient client)
{
if (client == null)
{
Console.WriteLine("Client is not connected.");
return;
}
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
string dataToSend = "Hello, Server!";
writer.WriteLine(dataToSend);
writer.Flush();
Console.WriteLine($"Sent: {dataToSend}");
string receivedData = reader.ReadLine();
Console.WriteLine($"Received: {receivedData}");
}
public static void Main(string[] args)
{
string serverAddress = "127.0.0.1"; // 服務器地址
int port = 8000; // 服務器端口號
TcpClient client = ConnectToServer(serverAddress, port);
if (client != null)
{
SendAndReceiveData(client);
client.Close();
}
}
注意:這只是一個簡單的示例,實際應用中需要考慮更多的錯誤處理和異常情況。同時,為了確保數據傳輸的完整性和安全性,可能需要對數據進行加密或使用其他安全措施。