20220510_191_upperpc/AutomaticApp/Models/ClientModel.cs

143 lines
3.9 KiB
C#
Raw Normal View History

2023-07-27 02:57:34 +00:00
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
{
/// <summary>
/// 客户端
/// </summary>
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;
/// <summary>
/// Socket通信是否连接
/// </summary>
public bool IsConnected
{
get { return isConnected; }
set { isConnected = value; this.DoNotify(); }
}
/// <summary>
/// 打开客户端连接
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <returns></returns>
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<byte>(buffer), stationName, 1);//1-卫通数据,用于区分
}
catch (Exception ex)
{
return;
}
}
}
#endregion
/// <summary>
/// 发送消息
/// </summary>
public void SendData(byte[] SendData)
{
_client.SendData(SendData);
}
}
public class SocketInfo : NotifyBase
{
private string ip;
/// <summary>
/// IP
/// </summary>
public string IP
{
get { return ip; }
set { ip = value; this.DoNotify(); }
}
private int port;
/// <summary>
/// 端口号
/// </summary>
public int Port
{
get { return port; }
set { port = value; this.DoNotify(); }
}
}
}