using AutomaticApp.Common; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using static AutomaticApp.Common.Sockets; namespace AutomaticApp.Models { /// /// 客户端 /// public class ClientModel : NotifyBase { SocketInfo SI = new SocketInfo(); public Clinet _client { set; get; } = new Clinet(); private BeiDouModel BeiDouModel { get; set; } = new BeiDouModel(); private bool isConnected; /// /// Socket通信是否连接 /// public bool IsConnected { get { return isConnected; } set { isConnected = value; this.DoNotify(); } } /// /// 打开客户端连接 /// /// /// /// public bool DoConnect(SocketInfo socketInfo) { //if (!tools.TelnetPort(socketInfo.IP, socketInfo.Port)) // return false; SI.IP = socketInfo.IP; SI.Port = socketInfo.Port; _client.InitSocket(socketInfo.IP, socketInfo.Port); //初始化设备的IP和端口号 IsConnected = _client.Connect(); if (IsConnected) { _client.pushSockets = ReceiveMess; } return IsConnected; } public bool DisConnect() { _client.Stop(); IsConnected = false; return IsConnected; } #region Socket通信接收 private void ReceiveMess(Sockets sks) { if (sks.ex != null) { if (sks.ClientDispose == true) { //由于未知原因引发异常.导致客户端下线. 比如网络故障.或服务器断开连接. //SetClientState(string.Format("客户端下线.!异常消息:{0}\r\n", sks.ex)); } else { //SetClientState(string.Format("异常消息:{0}\r\n", sks.ex)); } //timerConnect.Enabled = true; } else if (sks.Offset == 0) { //客户端主动下线 // SetClientState("客户端下线.!"); } else { byte[] buffer = new byte[sks.Offset]; Array.Copy(sks.RecBuffer, buffer, sks.Offset); try { int stationName = 0; if (SI.IP == tools.GetAppSetting("PLC_IP1")) { stationName = 1; } else if (SI.IP == tools.GetAppSetting("PLC_IP2")) { stationName = 2; } BeiDouModel.Data_nr(new List(buffer), stationName, 1);//1-卫通数据,用于区分 } catch (Exception ex) { return; } } } #endregion /// /// 发送消息 /// public void SendData(byte[] SendData) { _client.SendData(SendData); } } public class SocketInfo : NotifyBase { private string ip; /// /// IP /// public string IP { get { return ip; } set { ip = value; this.DoNotify(); } } private int port; /// /// 端口号 /// public int Port { get { return port; } set { port = value; this.DoNotify(); } } } }