using SKMC.Api.Common.Logger; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; namespace SKMC.Api.Common.Tcp { /// /// TCP Socket客户端 /// public class TCPClient { static readonly ILogger log = LogFactory.Get(); public int BufferSize { get; set; } = 1024 * 8; public string Address { get; set; } = "127.0.0.1"; public int Port { get; set; } public int Timeout { get; set; } = 10000; public bool KeepAlived { get; set; } public bool Logged { get; set; } = true; private Socket clientSocket; public TCPClient(string address, int port) { Address = address; Port = port; } public void Connect() { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, Timeout); clientSocket.Connect(new IPEndPoint(IPAddress.Parse(Address), Port)); log.Debug($"已连接至 {Address}:{Port}"); } public bool IsConnected(int millSeconds) { if (clientSocket == null) return false; //bool pollResult = clientSocket.Poll(1000 * millSeconds, SelectMode.SelectRead); //return pollResult && clientSocket.Available == 0; return true; } public void Close() { try { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } catch (Exception e) { log.Error("Socket连接关闭异常", e); } } public void Clear() { if (clientSocket.Available > 0) { clientSocket.Receive(new byte[clientSocket.Available]); } } public void Send(string msg, bool logged = true) { clientSocket.Send(Encoding.ASCII.GetBytes(msg)); if (Logged && logged) log.Debug($"已发送消息:\n{msg}"); } public string Recevie(bool logged = true) { byte[] buffer = new byte[BufferSize]; int length = clientSocket.Receive(buffer); string msg = Encoding.ASCII.GetString(buffer, 0, length); if (Logged && logged) log.Debug($"接收到消息:\n{msg}"); return msg; } public override string ToString() => $"address: {Address}, port: {Port}, keepAlive: {KeepAlived}, timeout: {Timeout}"; } }