dc/Common/SocketClient.cs
13118993771@163.com b593a243a5 V1.0
2022-07-27 14:46:20 +08:00

113 行
2.9 KiB
C#

#region << >>
/*----------------------------------------------------------------
* 创建者:13118
* 创建时间:2022/6/15 16:42:09
* 版本:V1.0.0
* 描述:
*
* ----------------------------------------------------------------
* 修改人:
* 时间:
* 修改说明:
*
* 版本:V1.0.1
*----------------------------------------------------------------*/
#endregion << >>
using Polly;
using Polly.Retry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ARI.EAP.HOST.Common
{
/// <summary>
/// SocketClient 的摘要说明
/// </summary>
public class SocketClient
{
private static Socket socket;
private Thread thread;
private byte[] buffer = new byte[2048];
private object sync_root = new object();
static SocketClient()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public SocketClient()
{
Task.Run(() => SocketConnect());
}
private void SocketConnect()
{
lock (sync_root)
{
RetryPolicy policy = Policy.Handle<SocketException>()
.WaitAndRetryForever(retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
{
});// 永远等待并重试,每次等待2的指数次冥的时间
policy.Execute(() =>
{
socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse("10086")));
thread = new Thread(StartReceive);
thread.IsBackground = true;
thread.Start(socket);
});
}
}
private void StartReceive(object obj)
{
string str;
while (true)
{
Socket receiveSocket = obj as Socket;
try
{
int result = receiveSocket.Receive(buffer);
if (result == 0)
{
break;
}
else
{
str = Encoding.Default.GetString(buffer);
}
}
catch (Exception ex)
{
}
}
}
public void Disconnected()
{
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
thread.Abort();
}
catch (Exception ex)
{
}
}
public void SendMessage(string message)
{
socket.Send(Encoding.Default.GetBytes(message));
}
}
}