| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355 |
- 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;
- using Toolkit.Log4;
- using static Toolkit.Tcp.TCPServer;
- namespace Toolkit.Tcp
- {
- public class TCPClient
- {
- /// <summary>
- /// 所有可以正常使用的连接
- /// </summary>
- public static List<TCPClient> sockets = new List<TCPClient>();
- public List<IPEndPoint> endps = new List<IPEndPoint>();
- public static bool createState = true;//创建是否成功
- public Socket socket;
- public string startstr;
- public string stopstr;
- public IPEndPoint iPEndPoint= new IPEndPoint(IPAddress.Parse("192.168.2.99"), 8888);//192.168.2.99
- public TCPClient()
- {
- Connect();
- }
- public void Connect()
- {
- try
- {
- AddressFamily addressFamily = AddressFamily.InterNetwork;
- SocketType socketType = SocketType.Stream;
- ProtocolType protocolType = ProtocolType.Tcp;
- socket = new Socket(addressFamily, socketType, protocolType);
- socket.Connect(iPEndPoint);
- LogHelper.Info(iPEndPoint.Address.ToString() + ":" + iPEndPoint.Port + " 已连接");
- socket.ReceiveTimeout = 2000;
- socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
- // 配置Keep-Alive参数(空闲3秒,间隔1秒,尝试3次)
- byte[] keepAliveParams = new byte[] {
- 1, 0, 0, 0, // 启用Keep-Alive
- 0x88, 0x13, 0, 0, // 空闲时间3000ms (十六进制0x00001388)
- 0xE8, 0x03, 0, 0, // 探测间隔1000ms (0x000003E8)
- 3, 0, 0, 0 // 探测次数3次
- };
- socket.IOControl(IOControlCode.KeepAliveValues, keepAliveParams, null);
- // 参数说明:空闲60秒后探测,间隔5秒,尝试3次 :ml-citation{ref="5,8" data="citationList"}
- // startstr = tcp.StartStr;
- //stopstr = tcp.StopStr;
- sockets.Add(this);
- createState = true;
- string str = ReceiveVarData(socket);
- LogHelper.Info(str);
- }
- catch
- {
- createState = false;
- if ( socket.Connected )
- {
- socket.Close();
- }
- }
- }
- public string SendAndReceive(string msg, int timeout = 2000)
- {
- try
- {
- byte[] msgbytes = Encoding.Default.GetBytes(msg);
- int i = socket.Send(msgbytes);
- byte[] bytes = new byte[256];
- i = socket.Receive(bytes);
- if ( i != 0 )
- {
- string str = Encoding.Default.GetString(bytes);
- str = str.Substring(0, i);
- int startindex = 0;
- int stopindex = 0;
- //if (startstr.Length != 0 && stopstr.Length != 0)
- //{
- // startindex = str.IndexOf(startstr);
- // stopindex = str.IndexOf(stopstr);
- //}
- //if (startindex != -1 && stopindex != -1)
- {
- // str = str.Substring(startindex + startstr.Length, stopindex - (startindex + startstr.Length));
- if ( str.Length != 0 )
- {
- LogHelper.Info("-" + socket.RemoteEndPoint.ToString() + ":" + str + "\r\n");
- return str;
- }
- else
- {
- return "ERROR";
- }
- }
- }
- return null;
- }
- catch ( Exception ex )
- {
- LogHelper.error.Error("", ex);
- return "";
- }
- }
- public string SendLinux(string NowSendData, int printcount = 1, int autostop = 0, int encode = 1)
- {
- string sends = "";
- byte[] endbyte = new byte[] { 00, 00, 03, 04 };
- if ( NowSendData != "" )
- {
- byte[] VerBin = new byte[10000];
- //计算校验字节。
- byte VerByte = 0;
- List<byte> CRCBuffer = new List<byte>();
- CRCBuffer.Add(0x1D); //起始
- CRCBuffer.Add(( byte ) ( printcount & 0xff ));
- CRCBuffer.Add(( byte ) ( ( printcount & 0xff00 ) >> 8 ));
- CRCBuffer.Add(( byte ) ( ( printcount & 0xff0000 ) >> 16 ));
- CRCBuffer.Add(( byte ) ( ( printcount & 0xff000000 ) >> 24 ));
- if ( autostop == 0 )
- CRCBuffer.Add(0x0A);
- else
- CRCBuffer.Add(0x0B);
- encode = 1; //220904统一采用utf8格式发送,解决部分gb2312乱码(二维码中)
- switch ( encode )
- {
- case 0:
- VerBin = System.Text.Encoding.GetEncoding("gb2312").GetBytes(NowSendData);
- CRCBuffer.Add(0xC1);
- break;
- case 1:
- VerBin = System.Text.Encoding.UTF8.GetBytes(NowSendData);
- CRCBuffer.Add(0xC2);
- break;
- case 2:
- VerBin = System.Text.Encoding.Unicode.GetBytes(NowSendData);
- CRCBuffer.Add(0xC3);
- break;
- }
- CRCBuffer.AddRange(VerBin); //数据
- VerByte = CRC8(CRCBuffer.ToArray());
- CRCBuffer.Add(VerByte);
- CRCBuffer.AddRange(endbyte);
- byte[] sendbuff = CRCBuffer.ToArray();
- LogHelper.Info(" 发送给打印机: outdata");
- string res = SendVarData(socket, Encoding.UTF8.GetBytes("outdata"));
- LogHelper.Info(" 打印机返回: " + res);
- if ( res != "Fail" && res != "Err" )
- {
- LogHelper.Info(" 发送给打印机: " + NowSendData);
- res = SendVarData(socket, sendbuff);
- LogHelper.Info(" 打印机返回: " + res);
- }
- return res;
- }
- else
- {
- return "null";
- }
- }
- public string ReceiveVarData(Socket s)
- {
- int total = 0;
- int recv;
- string datas = "";
- if ( s == null )
- return "未连接";
- if ( !s.Connected )
- {
- return "未连接";
- }
- int size = 0;
- byte[] datasize = new byte[4];
- try
- {
-
- recv = s.Receive(datasize, 0, 4, SocketFlags.None);
- }
- catch
- {
- return "未收到数据";
- }
- size = BitConverter.ToInt32(datasize, 0);
- if ( size == 0 )
- return "未收到数据";
- for ( int i = 0; i < datasize.Length; i++ )
- datas += datasize[ i ].ToString("X2") + " ";
- int dataleft = size;
- byte[] data = new byte[size];
- while ( total < size )
- {
- recv = s.Receive(data, total, dataleft, SocketFlags.None);
- if ( recv == 0 )
- {
- data = null;
- break;
- }
- total += recv;
- dataleft -= recv;
- }
- datas = "";
- return Encoding.UTF8.GetString(data);
- }
- public static byte CRC8(byte[] buffer)
- {
- byte crc = 0;
- for ( int j = 0; j < buffer.Length; j++ )
- {
- crc ^= buffer[ j ];
- for ( int i = 0; i < 8; i++ )
- {
- if ( ( crc & 0x01 ) != 0 )
- {
- crc >>= 1;
- crc ^= 0x8c;
- }
- else
- {
- crc >>= 1;
- }
- }
- }
- return crc;
- }
- public string SendVarData(Socket s, byte[] data)
- {
- if ( s == null )
- return "null";
- if ( !s.Connected )
- {
- return "未连接";
- }
- string datas = "";
- try
- {
- int total = 0;
- int size = data.Length;
- int dataleft = size;
- int sent;
- byte[] datasize = new byte[4];
- datasize = BitConverter.GetBytes(size);
- sent = s.Send(datasize);
- datas = "";
- while ( total < size )
- {
- sent = s.Send(data, total, dataleft, SocketFlags.None);
- total += sent;
- dataleft -= sent;
- }
- if ( total != 0 )
- {
- return "OK";
- }
- return "Fail";
- }
- catch ( Exception ex )
- {
- return "Err";
- }
- }
- public int Send(string msg, int timeout = 2000)
- {
- try
- {
- byte[] msgbytes = Encoding.Default.GetBytes(msg);
- int i = socket.Send(msgbytes);
- LogHelper.Info("本地发送数据:" + msg);
- return i;
- }
- catch ( Exception ex )
- {
- LogHelper.error.Error("", ex);
- return -1;
- }
- }
- public string Receive(int timeout = 2000)
- {
- try
- {
- byte[] bytes = new byte[256];
- int i = socket.Receive(bytes);
- if ( i != 0 )
- {
- return null;
- }
- return null;
- }
- catch ( Exception ex )
- {
- LogHelper.error.Error("", ex);
- return null;
- }
- }
- }
- }
|