using Invengo.Foundation.Util; using log4net; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace GDNXFD.WcfService { public class SocetClient { #region 单例方法 public static SocetClient Instance { get { return SingletonCreator.instance; } } class SingletonCreator { internal static readonly SocetClient instance = new SocetClient(); } #endregion private static ILog logger = LogManager.GetLogger("AppInfoLog"); private IPAddress _serverAddress = IPAddress.Parse("172.168.1.19"); private int _serverPort = 5050; private Socket _sock; private void Connect() { try { if (_sock == null) { _sock = new Socket(_serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } if (_sock.Connected) return; _sock.Connect(_serverAddress, _serverPort); } catch (Exception ex) { logger.WarnFormat("连接服务器失败!错误原因:{0}", ex.Message); _sock.Close(); _sock = null; } } private void ProcessConnect(IAsyncResult ar) { if (_sock != null && _sock.Connected) { logger.Info("连接服务器成功!"); //_sock.BeginReceive(_receiveBuffer, 0, MAX_BUFFER_SIZE, SocketFlags.None, ProcessReceive, null); } else { logger.WarnFormat("连接服务器失败!"); CloseSocket(); } } private void CloseSocket() { if (_sock != null) { //_sock.Shutdown(SocketShutdown.Send); _sock.Close(); _sock = null; logger.Info("连接断开!"); } } public void Send(byte[] msgBody) { byte[] frameB = new byte[] { 0x5a, 0x5a, 0x01, 0x01 }; byte[] lenB = BitConverter.GetBytes((short)(msgBody.Length + 6)); byte[] buffer = new byte[msgBody.Length + 6]; Array.Copy(frameB, buffer, 4); Array.Copy(lenB, 0, buffer, 4, 2); Array.Copy(msgBody, 0, buffer, 6, msgBody.Length); Connect(); if (_sock == null || !_sock.Connected) { logger.Info("发送失败!尚未建立与服务器的连接"); CloseSocket(); return; } try { _sock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, ProcessSend, buffer); } catch (Exception ex) { logger.ErrorFormat("发送失败!异常:{0}", ex.Message); } } private void ProcessSend(IAsyncResult iar) { byte[] buffer = (byte[])(iar.AsyncState); string hexString = CodeConvert.BytesToHexString(buffer, " "); logger.Info("发送数据:" + hexString); } } }