| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365 |
- 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 System.Timers;
- using System.Windows.Forms;
- using Timer = System.Timers.Timer;
- namespace Core.StlMes.Client.LgResMgt.Mcms
- {
- public class SocketClient : iCommunication
- {
- private Socket _socketClient;
- private Task sendTask;
- private readonly Timer timer = new Timer();
- public SocketClient()
- {
- timer.Elapsed += timer_Elapsed;
- timer.Interval = 1 * 5 * 1000;
- }
- private void timer_Elapsed(object sender, ElapsedEventArgs e)//判断是否连接成功
- {
- if(_socketClient==null) return;
- if (Reconnecting) return;
- if (Status && !Reconnect)
- {
- if (_socketClient.Connected)
- {
- try
- {
- byte[] temp = new byte[1]{0x00};
- // _socketClient.Send(temp, 0, 0);
- Reconnect = false;
- }
- catch (SocketException ex)
- {
- if (ex.NativeErrorCode.Equals(10035)) //仍然是connect的
- Reconnect = false;
- else
- Reconnect = true;
- }
- Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try
- {
- test.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
- }
- catch (SocketException ex)
- {
- if (ex.NativeErrorCode.Equals(10035)) //仍然是connect的
- Reconnect = false;
- else
- Reconnect = true;
- }
- finally
- {
- test.Disconnect(false);
- test.Shutdown(SocketShutdown.Both);
- test.Close();
- }
- }
- else
- {
- Reconnect = true;
- }
- }
- //连接已经断开
- if (Reconnect)
- {
- Reconnecting = true;
- OnReceiveDataA("0", "服务器断开,重量清0!", DataType.ReceiveData);
- OnReceiveDataA("0", "服务器断开,重新连接!", DataType.ClientReconnect);
- if (Status)
- {
- try
- {
- if (_socketClient != null)
- {
- _socketClient.Shutdown(SocketShutdown.Both);
- _socketClient.Close();
- _status = false;
- }
- }
- catch (Exception)
- {
- }
- }
- try
- {
- _socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //连接服务器
- _socketClient.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
- //请求获取数据
- _socketClient.Send(new byte[] { 0xE6, 0X00, 0XE7 });
- byte[] buffer = new byte[2048];
- _socketClient.ReceiveTimeout = 5000;
- int count = _socketClient.Receive(buffer);
- if (count <= 0 || !(buffer[0] == 0xE6 && buffer[1] == 0x00 && buffer[2] == 0xE7))
- {
- return;
- }
- _status = true;
- Reconnect = false;
- sendTask = new Task(() => StartReceive());
- sendTask.Start();
- OnReceiveDataA("", string.Format("开启监听 ip:{0} 端口:{1} ", Ip, Port), DataType.Open);
- }
- catch (Exception)
- {
- }
- Reconnecting = false;
- }
-
- }
- public void Start()
- {
- try
- {
- //实例化socket
- _socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-
-
- //连接服务器
- _socketClient.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
- //请求获取数据
- // _socketClient.Send(new byte[] { 0xE6, 0X00, 0XE7 });---
- // byte[] buffer = new byte[2048];--
- // _socketClient.ReceiveTimeout = 5000;--
- // int count = _socketClient.Receive(buffer);--
- /*
- if (count <= 0 || !(buffer[0] == 0xE6 && buffer[1] == 0x00 && buffer[2] == 0xE7))
- {
- MessageBox.Show("请求远程服务器失败!");
- return;
- }*/
- // timer.Start();
- _status = true;
- Reconnect = false;
- _socketClient.Blocking = true;
-
- sendTask = new Task(() => StartReceive());
- sendTask.Start();
- //OnReceiveDataA("", string.Format("开启监听 ip:{0} 端口:{1} ", Ip, Port), DataType.Open);
- }
- catch (Exception ex)
- {
- OnReceiveData(null, ex.Message, DataType.Error);
- }
- }
- /// <summary>
- /// 采用Socket方式,测试服务器连接
- /// </summary>
- /// <param name="host">服务器主机名或IP</param>
- /// <param name="port">端口号</param>
- /// <param name="millisecondsTimeout">等待时间:毫秒</param>
- /// <returns></returns>
- public static bool TestConnection(string host, int port)
- {
- int millisecondsTimeout = 5;//等待时间
- TcpClient client = new TcpClient();
- try
- {
- var ar = client.BeginConnect(host, port, null, null);
- ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
- return client.Connected;
- }
- catch (Exception e)
- {
- throw e;
- }
- finally
- {
- client.Close();
- }
- }
- public void Stop()
- {
- try
- {
- if (_socketClient != null)
- {
- _socketClient.Shutdown(SocketShutdown.Both);
- _socketClient.Close();
- }
- }
- catch (Exception)
- {
- }
- _status = false;
- Reconnect = false;
- timer.Stop();
- // OnReceiveDataA("", "断开与服务器的连接 ", DataType.Close);
- }
- /// <summary>
- /// 开启接收
- /// </summary>
- /// <param name="obj"></param>
- private void StartReceive()
- {
- var ReceiveData = new List<byte>();
- while (Status && !Reconnect)//
- {
- try
- {
- byte[] buffer = new byte[2048];
- int count = _socketClient.Receive(buffer);
- if (count > 0)
- {
- var Datas = buffer.ToList().Take(count);
- ReceiveData = ReceiveData.Concat(Datas).ToList();
- object Data;
- DeframeType Result = DeframeType.UnKnow;
- while (ReceiveData.Any() && Result != DeframeType.LengthLess)
- {
- List<Byte> rightData;
- Result = _protocol.AnalaysData(ReceiveData, out Data, out rightData);
- if (Result != DeframeType.RightFrame && Result != DeframeType.LengthLess) ReceiveData.Clear();
- if (Result == DeframeType.RightFrame)
- {
- OnReceiveData(Data, "成功解析数据!" + Data.ToString(), DataType.ReceiveData, rightData.ToArray());
- }
- if (Result == DeframeType.WrongFrame)
- {
- OnReceiveData(null, "数据解析失败", DataType.EvenMessage);
- }
- }
- }
- }
- catch (Exception ex)
- {
- // MessageBox.Show(ex.ToString());
- }
- }
- }
- public event ReceiveDataHandler ReceiveData;
- private IProtocol _protocol;
- public void ChangeProtocol(IProtocol iProtocol)
- {
- _protocol = iProtocol;
- }
- private bool _status;
- public bool Status {
- get { return _status || Reconnect; }
- }
- public bool Reconnect { get;private set; }
- public bool Reconnecting { get; private set; }
- protected virtual void OnReceiveData(object data, string message, DataType dataType, byte[] bData = null)
- {
- var handler = ReceiveData;
- if (handler != null)
- new Task(() => { handler(this, data, message, dataType, bData);
- if (dataType == DataType.ReceiveData)
- {
- double wt;
- if (double.TryParse(data.ToString2(), out wt))
- {
- WeightValue = (wt / 100d).ToString("0.00") + "t";
- };
- }
- }).Start();
- // handler(this, data, DeviceName + " " + message);
- }
-
- protected virtual void OnReceiveDataA(object data, string message, DataType dataType, byte[] bData = null)
- {
- var handler = ReceiveData;
- if (handler != null)
- handler(this, data, message, dataType, bData);
- // handler(this, data, DeviceName + " " + message);
- }
- public string Ip { get; set; }
-
- // public string SportNo { get; set; } //点位信息
- public bool Show { get; set; }//是否显示
- public string Port { get; set; }
- public string WeightValue { get; set; }//重量信息
-
- public override string ToString()
- {
- return "远程服务器[" + Ip + ":" + Port + "] ";
- }
- }
- }
|