C# 域套接字通讯类
生活随笔
收集整理的這篇文章主要介紹了
C# 域套接字通讯类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public class UdsClient
{
public Socket _socket { get; set; }
public UnixDomainSocketEndPoint endPoint = null;
public SocketInfo socketInfo = null;
public bool _isConnected = false; public delegate void OnConnectedHandler();
public event OnConnectedHandler OnConnected;
public event OnConnectedHandler OnFaildConnect;
public delegate void OnReceiveMsgHandler(string msg);
public event OnReceiveMsgHandler OnReceiveMsg;
public string Msg = ""; public UdsClient(string path)
{
endPoint = new UnixDomainSocketEndPoint(path);
_socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
} public void Start()
{
_socket.BeginConnect(endPoint, ConnectedCallback, _socket);
_isConnected = true;
Thread socketClient = new Thread(SocketClientReceive);
socketClient.IsBackground = true;
socketClient.Start();
} public void DisConnect()
{
_socket.Disconnect(true);
} public void SocketClientReceive()
{
Console.WriteLine("Uds SocketClientReceive begin");
while (_isConnected)
{
if (socketInfo == null)
{
Console.WriteLine("Uds當前連接成功,socketInfo null");
try
{
Console.WriteLine("Uds當前連接成功,創建接收SocketInfo");
socketInfo = new SocketInfo();
socketInfo.socket = _socket;
_socket.BeginReceive(socketInfo.buffer, 0, socketInfo.buffer.Length, SocketFlags.None, ReceiveCallback, socketInfo);
}
catch
{
_isConnected = false;
socketInfo?.socket?.Close();
socketInfo?.socket?.Dispose();
OnFaildConnect();
}
Console.WriteLine("Uds開始異步接收,延時100ms");
Thread.Sleep(100);
} }
Console.WriteLine("Uds SocketClientReceive end");
} public void ReceiveCallback(IAsyncResult ar)
{
Console.WriteLine("Uds ReceiveCallback begin");
socketInfo = ar.AsyncState as SocketInfo;
int readCount = 0;
try
{
if (socketInfo.socket == null) return;
readCount = socketInfo.socket.EndReceive(ar);
}
catch
{
return;
}
if (readCount > 0)
{
if (readCount < socketInfo.buffer.Length)
{
byte[] newBuffer = new byte[readCount];
Buffer.BlockCopy(socketInfo.buffer, 0, newBuffer, 0, readCount);
socketInfo.msgBuffer = newBuffer;
}
else
{
socketInfo.msgBuffer = socketInfo.buffer;
}
string msgTip = Encoding.UTF8.GetString(socketInfo.msgBuffer);
if (OnReceiveMsg != null) OnReceiveMsg(msgTip);
}
socketInfo.socket.Close();
socketInfo.socket.Dispose();
socketInfo = null;
Console.WriteLine("Uds ReceiveCallback end");
} public void ConnectedCallback(IAsyncResult ar)
{
Socket socket = ar.AsyncState as Socket;
if (socket.Connected)
{
if (this.OnConnected != null) OnConnected();
}
else
{
if (this.OnFaildConnect != null) OnFaildConnect();
}
} public void SendMsg(string msg)
{
byte[] buffer = Encoding.UTF8.GetBytes(msg);
_socket.Send(buffer);
} public class SocketInfo
{
public Socket socket = null;
public byte[] buffer = null;
public byte[] msgBuffer = null; public SocketInfo()
{
buffer = new byte[1024 * 4];
}
}
}
public class UdsForControl
{
private static readonly object _lockConnected = new object(); /// <summary>
/// 域套接字客戶端對象
/// </summary>
private static UdsClient _udsClient = null; /// <summary>
/// 域套接字文件地址
/// </summary>
private static string _path = ""; /// <summary>
/// 域套接字服務名稱
/// </summary>
private static string _name = ""; static UdsForControl()
{
var path = "UnixPath";
_name = "UnixServer";
//_path = Path.Combine(Path.GetTempPath(), path);
_path = path;
} public static void ConnectUdsServer()
{
lock (_lockConnected)
{
if (_udsClient == null)
{
var flag = true;
if (flag)
{
try
{
_udsClient = new UdsClient(_path);
_udsClient.OnConnected += _udsClient_OnConnected;
_udsClient.OnFaildConnect += _udsClient_OnFaildConnect;
_udsClient.OnReceiveMsg += _udsClient_OnReceiveMsg;
_udsClient.Start();
}
catch (Exception ex)
{
Console.WriteLine($"{_name}服務連接過程出現異常:{ex.Message}");
_udsClient_OnFaildConnect();
} } }
} } private static void _udsClient_OnFaildConnect()
{
lock (_lockConnected)
{
var flag = PublicMethod.GetConfigValue<bool>("UseUps");
if (flag)
{
Console.WriteLine($"{_name}服務斷線");
}
if (_udsClient != null)
{
Console.WriteLine($"Uds服務斷線,清理對象 _udsClient");
Clear(_udsClient);
}
if (BaseRepository.udsClient != null)
{
Console.WriteLine($"Uds服務斷線,清理對象 udsClient");
Clear(BaseRepository.udsClient);
}
}
} private static void Clear(UdsClient udsClient)
{
Console.WriteLine($"Uds服務斷線,Clear Begin");
//udsClient?._socket?.Shutdown(System.Net.Sockets.SocketShutdown.Both);
udsClient?._socket?.Close();
udsClient?._socket?.Dispose();
//udsClient?.socketInfo?.socket?.Shutdown(System.Net.Sockets.SocketShutdown.Both);
udsClient?.socketInfo?.socket?.Close();
udsClient?.socketInfo?.socket?.Dispose();
udsClient = null;
Console.WriteLine($"Uds服務斷線,Clear End");
} private static void _udsClient_OnConnected()
{
Console.WriteLine($"{_name}服務連接成功");
BaseRepository.udsClient = _udsClient;
} private static void _udsClient_OnReceiveMsg(string msg)
{
Console.WriteLine($"接收到{_name}消息:{msg}");
}
}
總結
以上是生活随笔為你收集整理的C# 域套接字通讯类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: strongswan技术
- 下一篇: iOS 点击推送消息跳转指定界面 —总结