用C#编写封装一个socket类,可以进行初始化,进行数据接收,数据发送,自动重连的功能的函数程序
时间: 2024-03-27 11:37:24 浏览: 40
以下是一个简单的C#封装的Socket类,包含了初始化、数据接收、数据发送、自动重连等功能。需要注意的是,这个类只是一个简单的示例,实际使用时可能需要根据具体需求进行修改和优化。
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class SocketClient
{
private Socket socket;
private string ip;
private int port;
private Thread receiveThread;
private byte[] receiveBuffer = new byte[1024];
private bool isConnected = false;
private bool isReconnecting = false;
public SocketClient(string ip, int port)
{
this.ip = ip;
this.port = port;
Init();
}
private void Init()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = true;
socket.ReceiveTimeout = 5000;
socket.SendTimeout = 5000;
Connect();
}
private void Connect()
{
try
{
socket.Connect(ip, port);
isConnected = true;
isReconnecting = false;
}
catch (Exception e)
{
Console.WriteLine("Socket Connect Error: " + e.ToString());
isConnected = false;
isReconnecting = true;
}
if (isConnected)
{
StartReceive();
}
else
{
Reconnect();
}
}
private void Reconnect()
{
if (!isReconnecting)
{
isReconnecting = true;
Thread.Sleep(5000);
Connect();
}
}
private void StartReceive()
{
receiveThread = new Thread(ReceiveThread);
receiveThread.Start();
}
private void ReceiveThread()
{
while (isConnected)
{
try
{
int count = socket.Receive(receiveBuffer);
if (count > 0)
{
string receiveStr = System.Text.Encoding.Default.GetString(receiveBuffer, 0, count);
Console.WriteLine("Socket Receive: " + receiveStr);
}
}
catch (Exception e)
{
Console.WriteLine("Socket Receive Error: " + e.ToString());
isConnected = false;
isReconnecting = true;
break;
}
}
if (isConnected)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
else
{
Reconnect();
}
}
public void Send(string sendStr)
{
try
{
byte[] sendBuffer = System.Text.Encoding.Default.GetBytes(sendStr);
socket.Send(sendBuffer);
Console.WriteLine("Socket Send: " + sendStr);
}
catch (Exception e)
{
Console.WriteLine("Socket Send Error: " + e.ToString());
isConnected = false;
isReconnecting = true;
}
}
}
```
使用示例:
```csharp
SocketClient client = new SocketClient("127.0.0.1", 8888);
client.Send("Hello World!");
// 等待5秒钟
Thread.Sleep(5000);
client.Send("Hello Again!");
```
阅读全文