逻辑处理
- 创建一个Socket对象并连接到服务器,可以使用Socket.Connect()方法。
- 使用Socket.Send()方法发送数据到服务器。
- 使用Socket.Receive()方法接收服务器返回的数据。
- 实现心跳检测,可以定时向服务器发送一个心跳包,如果服务器没有响应,则说明连接已断开。
- 如果连接断开,可以尝试重新连接,可以使用Socket.Close()方法关闭当前连接,然后再重新创建一个新的Socket对象。
注意事项:
- 长连接需要保证数据传输的可靠性,可以考虑使用TCP协议。
- 心跳检测的频率需要根据具体情况进行调整,过于频繁可能会增加网络负担,过于稀疏可能会延迟发现连接异常。
- 在使用Socket的过程中,需要考虑异常处理和资源释放问题,避免出现内存泄漏等问题。
代码示例1:
using System; using System.Net.Sockets; class Program { static void Main(string[] args) { string serverIp = "127.0.0.1"; int serverPort = 12345; // 创建 Socket 对象并连接到服务器 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(serverIp, serverPort); // 发送数据并接收服务器返回的数据 byte[] sendData = System.Text.Encoding.UTF8.GetBytes("Hello, world!"); socket.Send(sendData); byte[] recvData = new byte[1024]; int recvSize = socket.Receive(recvData); string recvMsg = System.Text.Encoding.UTF8.GetString(recvData, 0, recvSize); Console.WriteLine("[Server]: {0}", recvMsg); // 定时发送心跳包并检测连接状态 while (true) { try { // 发送心跳包 byte[] heartbeatData = System.Text.Encoding.UTF8.GetBytes("heartbeat"); socket.Send(heartbeatData); // 接收服务器返回的心跳包响应 byte[] heartbeatResp = new byte[1024]; int respSize = socket.Receive(heartbeatResp); if (respSize == 0) { throw new Exception("Connection failed: no response received."); } string respMsg = System.Text.Encoding.UTF8.GetString(heartbeatResp, 0, respSize); Console.WriteLine("[Server]: {0}", respMsg); // 等待一段时间后再次发送心跳包 System.Threading.Thread.Sleep(5000); } catch (Exception ex) { Console.WriteLine(ex.Message); // 连接断开,关闭当前连接并尝试重新连接 socket.Close(); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(serverIp, serverPort); } } } }
代码示例2:
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main(string[] args)
{
string serverIp = "127.0.0.1";
int serverPort = 12345;
string logFile = @"C:\log.txt";
// 创建 Socket 对象并连接到服务器
Log("Connecting to server...");
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect(serverIp, serverPort);
Log("Connected to server.");
}
catch (Exception ex)
{
Log("Connection failed: " + ex.Message);
return;
}
// 发送数据并接收服务器返回的数据
byte[] sendData = Encoding.UTF8.GetBytes("Hello, world!");
try
{
Log("Sending data to server...");
socket.Send(sendData);
byte[] recvData = new byte[1024];
int recvSize = socket.Receive(recvData);
string recvMsg = Encoding.UTF8.GetString(recvData, 0, recvSize);
Log("[Server]: " + recvMsg);
}
catch (Exception ex)
{
Log("Error sending or receiving data: " + ex.Message);
socket.Close();
return;
}
// 定时发送心跳包并检测连接状态
while (true)
{
try
{
// 发送心跳包
byte[] heartbeatData = Encoding.UTF8.GetBytes("heartbeat");
socket.Send(heartbeatData);
Log("Sent heartbeat.");
// 接收服务器返回的心跳包响应
byte[] heartbeatResp = new byte[1024];
int respSize = socket.Receive(heartbeatResp);
if (respSize == 0)
{
throw new Exception("Connection failed: no response received.");
}
string respMsg = Encoding.UTF8.GetString(heartbeatResp, 0, respSize);
Log("[Server]: " + respMsg);
// 等待一段时间后再次发送心跳包
System.Threading.Thread.Sleep(5000);
}
catch (Exception ex)
{
Log("Error sending or receiving heartbeat: " + ex.Message);
// 连接断开,关闭当前连接并尝试重新连接
socket.Close();
Log("Disconnected from server. Trying to reconnect...");
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(serverIp, serverPort);
Log("Connected to server.");
}
catch (Exception ex2)
{
Log("Reconnection failed: " + ex2.Message);
}
}
}
}
static void Log(string message)
{
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string logMessage = "[" + timestamp + "] " + message;
Console.WriteLine(logMessage);
using (StreamWriter writer = File.AppendText(@"C:\log.txt"))
{
writer.WriteLine(logMessage);
}
}
}
单客户端连接多服务器代码示例
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class Client {
// 声明变量
private static List<TcpClient> clients = new List<TcpClient>(); // 多个服务端
private static bool run = true; // 运行状态
private static bool connected = false; // 连接状态
private static StreamWriter logFile; // 日志文件
static void Main(string[] args) {
// 创建日志文件
logFile = new StreamWriter("log.txt", true);
logFile.AutoFlush = true;
// 连接多个服务端
Connect("192.168.0.1", 5000);
Connect("192.168.0.2", 5000);
// 执行心跳检测和断线重连
while (run) {
if (!connected) {
// 断线重连
Reconnect();
} else {
// 执行心跳检测
foreach (TcpClient client in clients) {
if (client.Connected) {
NetworkStream stream = client.GetStream();
byte[] message = System.Text.Encoding.ASCII.GetBytes("PING");
stream.Write(message, 0, message.Length);
}
}
Thread.Sleep(10000); // 等待10秒
}
}
// 关闭日志文件
logFile.Close();
}
static void Connect(string ip, int port) {
try {
TcpClient client = new TcpClient(ip, port);
clients.Add(client);
connected = true;
logFile.WriteLine("Connected to " + ip + ":" + port);
// 启动接收线程
Thread receiveThread = new Thread(new ParameterizedThreadStart(Receive));
receiveThread.Start(client);
} catch (Exception e) {
logFile.WriteLine("Error connecting to " + ip + ":" + port + " - " + e.Message);
}
}
static void Reconnect() {
logFile.WriteLine("Trying to reconnect...");
foreach (TcpClient client in clients) {
try {
if (!client.Connected) {
client.Connect(((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString(), ((IPEndPoint)client.Client.RemoteEndPoint).Port);
connected = true;
logFile.WriteLine("Reconnected to " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString() + ":" + ((IPEndPoint)client.Client.RemoteEndPoint).Port);
// 启动接收线程
Thread receiveThread = new Thread(new ParameterizedThreadStart(Receive));
receiveThread.Start(client);
}
} catch (Exception e) {
logFile.WriteLine("Error reconnecting to " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString() + ":" + ((IPEndPoint)client.Client.RemoteEndPoint).Port + " - " + e.Message);
}
}
Thread.Sleep(5000); // 等待5秒
}
static void Receive(object clientObject) {
TcpClient client = (TcpClient)clientObject;
NetworkStream stream = client.GetStream();
byte[] message = new byte[1024];
int bytesRead;
while (run) {
try {
bytesRead = stream.Read(message, 0, message.Length);
if (bytesRead > 0) {
string data = System.Text.Encoding.ASCII.GetString(message, 0, bytesRead);
logFile.WriteLine("Received data: " + data);
}
} catch (Exception e) {
connected = false;
logFile.WriteLine("Error receiving data from " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString() + ":" + ((IPEndPoint)client.Client.RemoteEndPoint).Port + " - " + e.Message);
break;
}
}
}
}