1 public class SocketTcpClient 2 { 3 public static string ErrorMsg = string.Empty; 4 private static Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 5 private static string _serverIp = string.Empty; 6 private static int _port = 2020; 7 private static int _state = 0; 8 private static readonly int _timeout = 10; 9 10 private static void ClearSocket() 11 { 12 if (_socket != null) 13 { 14 _socket.Close(); 15 } 16 _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 17 } 18 19 private static bool Connect() 20 { 21 try 22 { 23 if (!_socket.Connected) 24 { 25 IPEndPoint ep = new IPEndPoint(IPAddress.Parse(_serverIp), _port); 26 _socket.Connect(ep); 27 Thread.Sleep(10); 28 } 29 return true; 30 31 } 32 catch (System.Exception ex) 33 { 34 ClearSocket(); 35 ErrorMsg = "网络错误!原因:" + ex.Message; 36 return false; 37 } 38 } 39 40 private static bool Send(byte[] byteArray) 41 { 42 bool bConnect = _socket.Connected; 43 if (!bConnect) 44 bConnect = Connect(); 45 46 if (bConnect) 47 { 48 try 49 { 50 var numberOfBytesSent = _socket.Send(byteArray); 51 if (numberOfBytesSent == 0) 52 { 53 ClearSocket(); 54 ErrorMsg = "网络错误!原因:发送时对方关闭socket连接"; 55 return false; 56 } 57 return true; 58 } 59 catch (System.Exception ex) 60 { 61 ClearSocket(); 62 ErrorMsg = "网络错误!原因:" + ex.Message; 63 return false; 64 } 65 } 66 return false; 67 } 68 69 private static bool Receive(ref byte[] byteArray) 70 { 71 bool bConnect = _socket.Connected; 72 if (!bConnect) 73 bConnect = Connect(); 74 75 if (bConnect) 76 { 77 MemoryStream ms = new MemoryStream(); 78 byte[] readBuffer = new byte[1024*8]; 79 80 do 81 { 82 var numberOfBytesRead = 0; 83 try 84 { 85 numberOfBytesRead = _socket.Receive(readBuffer); 86 } 87 catch (System.Exception ex) 88 { 89 ClearSocket(); 90 ErrorMsg = "网络错误!原因:" + ex.Message; 91 return false; 92 } 93 94 //对方关闭socket连接,上面的Read函数据阻塞取消,收到数据为0 95 if (numberOfBytesRead == 0) 96 { 97 ClearSocket(); 98 ErrorMsg = "网络错误!原因:接收时对方关闭socket连接"; 99 return false; 100 } 101 102 //增加接收到的数据,并转化为MemoryStream 103 ms.Write(readBuffer, 0, numberOfBytesRead); 104 105 } while (_socket.Connected && _socket.Available > 0); 106 107 byteArray = ms.ToArray(); 108 return true; 109 } 110 return false; 111 } 112 113 private static void RunWorkThread(object stateInfo) 114 { 115 DateTime dt = (DateTime) stateInfo; 116 while (true) 117 { 118 Thread.Sleep(100); 119 TimeSpan ts = DateTime.Now - dt; 120 if (_state == 1) 121 { 122 if (ts.Seconds > _timeout) 123 { 124 ClearSocket(); 125 _state = 2; 126 break; 127 } 128 } 129 else 130 { 131 break; 132 } 133 } 134 } 135 136 private static bool SysCall(byte[] dataRequest, ref byte[] dataResponse) 137 { 138 _state = 1; 139 ThreadPool.QueueUserWorkItem(RunWorkThread, DateTime.Now); 140 141 bool bResult = false; 142 if (Send(dataRequest)) 143 { 144 bResult = Receive(ref dataResponse); 145 } 146 147 if (_state == 2) 148 { 149 ErrorMsg = "超时错误!"; 150 } 151 else 152 { 153 _state = 0; 154 } 155 return bResult; 156 } 157 158 /// <summary> 159 /// 同步传输 160 /// </summary> 161 /// <param name="controller"></param> 162 /// <param name="action"></param> 163 /// <param name="msg">utf-8</param> 164 /// <returns></returns> 165 public static string SyncCallMessage(string controller, string action, string msg) 166 { 167 byte[] msgRequest = Encoding.UTF8.GetBytes(controller + " " + action + " " + msg + Environment.NewLine); 168 byte[] result = null; 169 string msgResult = null; 170 171 //同步调用远程方法 172 bool bSuccess = SysCall(msgRequest, ref result); 173 if (bSuccess) 174 { 175 msgResult = Encoding.UTF8.GetString(result); 176 } 177 return msgResult; 178 } 179 180 public static void SetServerIp(string serverIp, int port) 181 { 182 _serverIp = serverIp; 183 _port = port; 184 ClearSocket(); 185 } 186 }
1 public static class JsonConvert 2 { 3 public static string ToJsonEx(this object dto) 4 { 5 return Newtonsoft.Json.JsonConvert.SerializeObject(dto); 6 } 7 8 public static T FromJsonEx<T>(this string json) 9 { 10 return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json); 11 } 12 }
主要用在Pda开发数据通信方式,当然在Pda上用webrequest,拿到json解析也可以,以上Socket请求服务是同步的,如果需要稍微改善下,异步接收数据,那么服务器可以做到推送消息。