在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();
}
}
注意:这只是一个简单的示例,实际应用中需要考虑更多的错误处理和异常情况。同时,为了确保数据传输的完整性和安全性,可能需要对数据进行加密或使用其他安全措施。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>