752 lines
21 KiB
C#
752 lines
21 KiB
C#
using Community;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using System.Windows;
|
||
|
||
namespace Model
|
||
{
|
||
/// <summary>
|
||
/// 通讯类
|
||
/// </summary>
|
||
public class CommunicationManagementClass : NotificationObject
|
||
{
|
||
#region 基础参数
|
||
public int ID { get; set; }
|
||
/// <summary>
|
||
/// 软件ID
|
||
/// </summary>
|
||
public int SoftID { get; set; }
|
||
|
||
private string actionName;
|
||
/// <summary>
|
||
/// 作用名称
|
||
/// </summary>
|
||
public string ActionName
|
||
{
|
||
get { return actionName; }
|
||
set
|
||
{
|
||
actionName = value;
|
||
Names = value;
|
||
TempName = value;
|
||
this.RaisePropertyChanged("ActionName");
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 简码 用于发给服务器进行身份识别
|
||
/// </summary>
|
||
public string ShortCode { get; set; }
|
||
|
||
/// <summary>
|
||
/// 主动发送身份识别码
|
||
/// </summary>
|
||
public bool SendShortCode { get; set; }
|
||
|
||
|
||
#region IP
|
||
private string ip;
|
||
/// <summary>
|
||
/// IP地址
|
||
/// </summary>
|
||
public string IP
|
||
{
|
||
get { return ip; }
|
||
set
|
||
{
|
||
ip = value;
|
||
this.RaisePropertyChanged("IP");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region Port端口号
|
||
private int port;
|
||
/// <summary>
|
||
/// Port端口号
|
||
/// </summary>
|
||
public int Port
|
||
{
|
||
get { return port; }
|
||
set
|
||
{
|
||
port = value;
|
||
this.RaisePropertyChanged("Port");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 是否为服务器通讯连接
|
||
/// </summary>
|
||
public bool InServer { get; set; }
|
||
|
||
private bool activeConnection;
|
||
/// <summary>
|
||
/// 主动连接
|
||
/// </summary>
|
||
public bool ActiveConnection
|
||
{
|
||
get { return activeConnection; }
|
||
set
|
||
{
|
||
activeConnection = value;
|
||
ConnButtonShow = value ? Visibility.Visible : Visibility.Collapsed;
|
||
this.RaisePropertyChanged("ActiveConnection");
|
||
}
|
||
}
|
||
|
||
private Visibility connButtonShow;
|
||
/// <summary>
|
||
/// 是否显示连接按钮
|
||
/// </summary>
|
||
public Visibility ConnButtonShow
|
||
{
|
||
get { return connButtonShow; }
|
||
set
|
||
{
|
||
connButtonShow = value;
|
||
this.RaisePropertyChanged("ConnButtonShow");
|
||
}
|
||
}
|
||
|
||
|
||
|
||
|
||
/// <summary>
|
||
/// 通过端口号识别身份,但此字段为True时,Ip与Port需一致 从而确认客户端身份
|
||
/// </summary>
|
||
public bool PortDis { get; set; }
|
||
|
||
|
||
private bool redeive16;
|
||
/// <summary>
|
||
/// 是否16进制接收
|
||
/// </summary>
|
||
public bool Redeive16
|
||
{
|
||
get { return redeive16; }
|
||
set
|
||
{
|
||
redeive16 = value;
|
||
this.RaisePropertyChanged("Redeive16");
|
||
}
|
||
}
|
||
|
||
private bool send16;
|
||
/// <summary>
|
||
/// 是否是16进制发送
|
||
/// </summary>
|
||
public bool Send16
|
||
{
|
||
get { return send16; }
|
||
set
|
||
{
|
||
send16 = value;
|
||
this.RaisePropertyChanged("Send16");
|
||
}
|
||
}
|
||
|
||
private bool isUDP;
|
||
/// <summary>
|
||
/// 是否是UDP 协议
|
||
/// </summary>
|
||
public bool IsUDP
|
||
{
|
||
get { return isUDP; }
|
||
set
|
||
{
|
||
isUDP = value;
|
||
this.RaisePropertyChanged("IsUDP");
|
||
}
|
||
}
|
||
|
||
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 消息状态委托
|
||
/// </summary>
|
||
public delegate void delegateReceivePower(string str);
|
||
/// <summary>
|
||
/// 消息传递时间
|
||
/// </summary>
|
||
public event delegateReceivePower ReceiveCallback;
|
||
/// <summary>
|
||
/// 通信套接字
|
||
/// </summary>
|
||
public Socket ConnSocket { get; set; }
|
||
|
||
#region 发送的字符串内容
|
||
private string sendStr;
|
||
/// <summary>
|
||
/// 发送的字符串内容
|
||
/// </summary>
|
||
public string SendStr
|
||
{
|
||
get { return sendStr; }
|
||
set
|
||
{
|
||
sendStr = value;
|
||
this.RaisePropertyChanged("SendStr");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 接收到的字符串信息
|
||
private string receiveInfo;
|
||
/// <summary>
|
||
/// 接收到的字符串信息
|
||
/// </summary>
|
||
public string ReceiveInfo
|
||
{
|
||
get { return receiveInfo; }
|
||
set
|
||
{
|
||
receiveInfo = value;
|
||
try
|
||
{
|
||
if (!string.IsNullOrEmpty(value))
|
||
{
|
||
ReceiveCallback(ReceiveInfo);
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
|
||
this.RaisePropertyChanged("ReceiveInfo");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
|
||
#region 连接开关
|
||
private bool connectSwitch;
|
||
/// <summary>
|
||
/// 连接开关
|
||
/// </summary>
|
||
public bool ConnectSwitch
|
||
{
|
||
get { return connectSwitch; }
|
||
set
|
||
{
|
||
connectSwitch = value;
|
||
ReconnectSwitch = false;
|
||
this.RaisePropertyChanged("ConnectSwitch");
|
||
if (value && this.ActiveConnection)
|
||
{
|
||
OpenConn();
|
||
}
|
||
else
|
||
{
|
||
CloseConn();
|
||
}
|
||
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 是否需要重新连接
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public bool ReconnectSwitch { get; set; }
|
||
#endregion
|
||
|
||
#region 连接状态
|
||
private ShowInfo showmsg;
|
||
/// <summary>
|
||
/// 连接状态
|
||
/// </summary>
|
||
public ShowInfo Showmsg
|
||
{
|
||
get { return showmsg; }
|
||
set
|
||
{
|
||
showmsg = value;
|
||
this.RaisePropertyChanged("Showmsg");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
|
||
#region 连接对象名称
|
||
private string names;
|
||
/// <summary>
|
||
/// 连接对象名称
|
||
/// </summary>
|
||
public string Names
|
||
{
|
||
get { return names; }
|
||
set
|
||
{
|
||
names = value;
|
||
this.RaisePropertyChanged("Names");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 构造函数
|
||
/// <summary>
|
||
/// 构造函数
|
||
/// </summary>
|
||
/// <param name="ip">IP地址</param>
|
||
/// <param name="port">端口号</param>
|
||
public CommunicationManagementClass(string ip, int port)
|
||
{
|
||
IP = ip;
|
||
Port = port;
|
||
// OpenConn();
|
||
// OpenReceivesMassage();//开启数据接收
|
||
|
||
Showmsg = new ShowInfo();
|
||
Showmsg.StatuInfo = "等待连接";
|
||
Showmsg.StatusBackground = ColorStr.Gray;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
|
||
}
|
||
|
||
|
||
public string TempName = "";
|
||
/// <summary>
|
||
/// 构造函数的重载
|
||
/// </summary>
|
||
/// <param name="userid">连接过来的客户端对象</param>
|
||
/// <param name="sockeing">客户端通信套接字</param>
|
||
public CommunicationManagementClass(Socket sockeing, string userName, string names)
|
||
{
|
||
Showmsg = new ShowInfo();
|
||
|
||
this.ConnSocket = sockeing;
|
||
this.ShortCode = userName;
|
||
this.Names = names;
|
||
TempName = names;
|
||
|
||
OpenReceivesMassage();//开启数据接收
|
||
|
||
|
||
Showmsg.StatuInfo = "连接正常";
|
||
Showmsg.StatusBackground = ColorStr.Green;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
|
||
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// 无参构造函数
|
||
/// </summary>
|
||
public CommunicationManagementClass()
|
||
{
|
||
Showmsg = new ShowInfo();
|
||
Showmsg.StatuInfo = "等待连接";
|
||
Showmsg.StatusBackground = ColorStr.Gray;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
ConnButtonShow = Visibility.Collapsed;
|
||
this.InServer = false;
|
||
|
||
}
|
||
#endregion
|
||
|
||
#region 开启数据接收
|
||
/// <summary>
|
||
/// 开启数据接收
|
||
/// </summary>
|
||
public void OpenReceivesMassage()
|
||
{
|
||
ConnSocket.BeginReceive(Buffes, 0, Buffes.Length, 0, new AsyncCallback(ReadCallback), ConnSocket);
|
||
}
|
||
/// <summary>
|
||
/// 接收到的字节
|
||
/// </summary>
|
||
public byte[] Buffes = new byte[1024 * 1024 * 5];
|
||
/// <summary>
|
||
/// 数据接收
|
||
/// </summary>
|
||
/// <param name="ar">请求的Socket</param>
|
||
private void ReadCallback(IAsyncResult ar)
|
||
{
|
||
try
|
||
{
|
||
ConnSocket = ar.AsyncState as Socket;
|
||
int lenght = ConnSocket.EndReceive(ar);
|
||
|
||
if (lenght > 0)
|
||
{
|
||
//string ReceiveStr = System.Text.Encoding.UTF8.GetString(Buffes, 0, lenght);
|
||
|
||
//string ReceiveStr16 = BitConverter.ToString(Buffes, 0, lenght);//.Replace("-", " ");
|
||
|
||
if (Redeive16)
|
||
{
|
||
ReceiveInfo = BitConverter.ToString(Buffes, 0, lenght);
|
||
}
|
||
else
|
||
{
|
||
ReceiveInfo = System.Text.Encoding.UTF8.GetString(Buffes, 0, lenght);
|
||
}
|
||
|
||
//接收完成 重新给出buffer接收
|
||
Buffes = new byte[1024 * 1024 * 5];
|
||
ConnSocket.BeginReceive(Buffes, 0, Buffes.Length, 0, new AsyncCallback(ReadCallback), ConnSocket);
|
||
}
|
||
else
|
||
{
|
||
Names = Names + "(已断开)";
|
||
Showmsg.StatuInfo = "连接中断!";
|
||
Showmsg.StatusBackground = ColorStr.Red;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
//CloseConn();
|
||
//OpenConn();//重新连接
|
||
if (ActiveConnection)
|
||
{
|
||
ConnectSwitch = false;
|
||
ConnectSwitch = true;//重新连接
|
||
}
|
||
|
||
}
|
||
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Names = Names + "(已断开)";
|
||
Showmsg.StatuInfo = "连接中断!" + ex.Message;
|
||
Showmsg.StatusBackground = ColorStr.Red;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
|
||
if (ActiveConnection)
|
||
{
|
||
ConnectSwitch = false;
|
||
ConnectSwitch = true;//重新连接
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 开启连接
|
||
|
||
public ManualResetEvent allDone = new ManualResetEvent(false);
|
||
IPAddress Address;
|
||
IPEndPoint Endpoint;
|
||
|
||
/// <summary>
|
||
/// 开启连接
|
||
/// </summary>
|
||
public void OpenConn()
|
||
{
|
||
try
|
||
{
|
||
if (ConnSocket == null)
|
||
{
|
||
if (IsUDP)
|
||
{
|
||
//1.创建监听套接字 使用ip4协议 流式传输 Udp连接
|
||
ConnSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||
|
||
}
|
||
else
|
||
{
|
||
//1.创建监听套接字 使用ip4协议 流式传输 tcp连接
|
||
ConnSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||
// 获取服务器端口
|
||
Address = IPAddress.Parse(IP);
|
||
Endpoint = new IPEndPoint(Address, Port);
|
||
|
||
Showmsg.StatuInfo = "连接尝试中...";
|
||
Showmsg.StatusBackground = ColorStr.Yellow;
|
||
Showmsg.StatusForeground = ColorStr.Black;
|
||
//allDone.Reset();
|
||
////开启异步连接服务器
|
||
ConnSocket.BeginConnect(Endpoint, new AsyncCallback(ConnectCallback), ConnSocket);
|
||
//allDone.WaitOne();
|
||
}
|
||
}
|
||
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Showmsg.StatuInfo = "连接失败" + ex.Message;
|
||
Showmsg.StatusBackground = ColorStr.Red;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
|
||
}
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// 异步连接
|
||
/// </summary>
|
||
/// <param name="ar"></param>
|
||
private void ConnectCallback(IAsyncResult ar)
|
||
{
|
||
try
|
||
{
|
||
//allDone.Set();
|
||
// ConnSocket = (Socket)ar.AsyncState;
|
||
if (ConnSocket!=null &&ConnSocket.Connected)
|
||
{
|
||
ConnSocket.EndConnect(ar);//挂起异步连接
|
||
|
||
if (SendShortCode)
|
||
{
|
||
//发送自己的UserId给被连接对象
|
||
SendInfo(ShortCode);
|
||
}
|
||
//开始接收数据
|
||
OpenReceivesMassage();
|
||
|
||
Showmsg.StatuInfo = "连接正常";
|
||
Showmsg.StatusBackground = ColorStr.Green;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
|
||
}
|
||
else
|
||
{
|
||
Showmsg.StatuInfo = "重连中...";
|
||
Showmsg.StatusBackground = ColorStr.Red;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
//重连
|
||
if (ConnSocket != null ) ConnSocket.BeginConnect(Endpoint, new AsyncCallback(ConnectCallback), ConnSocket);
|
||
|
||
}
|
||
|
||
}
|
||
catch
|
||
{
|
||
//重新连接
|
||
ReconnectSwitch = true;
|
||
}
|
||
}
|
||
|
||
|
||
#endregion
|
||
|
||
#region 关闭连接
|
||
/// <summary>
|
||
/// 关闭连接
|
||
/// </summary>
|
||
public void CloseConn()
|
||
{
|
||
try
|
||
{
|
||
if (ConnSocket != null)
|
||
{
|
||
ConnSocket.Close(); //关闭套接字
|
||
ConnSocket = null;
|
||
|
||
Showmsg.StatuInfo = "未连接!";
|
||
Showmsg.StatusBackground = ColorStr.Red;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 发送消息
|
||
/// <summary>
|
||
/// 发送消息
|
||
/// </summary>
|
||
/// <param name="str">发送内容</param>
|
||
public void SendInfo(string str)
|
||
{
|
||
try
|
||
{
|
||
//byte[] sendbyte1 = HexToBytes(SendStr);
|
||
//byte[] sendbyte2 = Encoding.UTF8.GetBytes(str);
|
||
if (!string.IsNullOrEmpty(str))
|
||
{
|
||
//如果连接断开了 就重连
|
||
if (Showmsg.StatusBackground != ColorStr.Green && ActiveConnection)
|
||
{
|
||
OpenConn();
|
||
}
|
||
ReceiveInfo = "";
|
||
if (Send16)
|
||
{
|
||
SendStr = str;
|
||
byte[] sendbyte = HexToBytes(SendStr);
|
||
ConnSocket.Send(sendbyte);
|
||
}
|
||
else
|
||
{
|
||
SendStr = str;
|
||
byte[] sendbyte = Encoding.UTF8.GetBytes(str);
|
||
ConnSocket.Send(sendbyte);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 字符串转16进制
|
||
/// <summary>
|
||
/// 字符串转16进制
|
||
/// </summary>
|
||
/// <param name="str"></param>
|
||
/// <returns></returns>
|
||
private byte[] StringToBytes(string str)
|
||
{
|
||
try //尝试将发送的数据转为16进制Hex
|
||
{
|
||
str = StringToHex(str.Trim());
|
||
return HexToBytes(str);
|
||
}
|
||
catch //无法转为16进制时,出现异常
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// string转Hex
|
||
/// </summary>
|
||
/// <param name="s"></param>
|
||
/// <returns></returns>
|
||
public static string StringToHex(string s)
|
||
{
|
||
s = Regex.Unescape(s); //删除转义符
|
||
|
||
//byte[] bytes = System.Text.Encoding.Default.GetBytes(s);
|
||
|
||
//string str = "";
|
||
|
||
//for (int i = 0; i < bytes.Length; i++)
|
||
//{
|
||
// string a = string.Format("{0:X}", bytes[i]);
|
||
// a = a.Length > 1 ? a : "0" + a;
|
||
// str += a + " ";
|
||
|
||
//}
|
||
string str = string.Join("-", s.Select(c => ((int)c).ToString("X2")));
|
||
return str;
|
||
}
|
||
|
||
/// <summary>
|
||
/// hex转string
|
||
/// </summary>
|
||
/// <param name="hex"></param>
|
||
/// <returns></returns>
|
||
private string HexToString(string hex)
|
||
{
|
||
|
||
|
||
string[] strArr = hex.Trim().Split('-');
|
||
byte[] b = new byte[strArr.Length];
|
||
//逐个字符变为16进制字节数据
|
||
for (int i = 0; i < strArr.Length; i++)
|
||
{
|
||
b[i] = Convert.ToByte(strArr[i], 16);
|
||
}
|
||
|
||
//按照指定编码将字节数组变为字符串
|
||
return System.Text.Encoding.Default.GetString(b);
|
||
}
|
||
|
||
/// <summary>
|
||
/// hex转byte[]
|
||
/// </summary>
|
||
/// <param name="hs"></param>
|
||
/// <returns></returns>
|
||
public static byte[] HexToBytes(string hs)
|
||
{
|
||
|
||
if (!hs.Contains("-"))
|
||
{
|
||
hs = Regex.Replace(hs, @"(\w{2})", "$1-").Trim('-'); //字符串每隔2位加一个空格
|
||
}
|
||
|
||
string[] strArr = hs.Trim().Split('-');
|
||
byte[] b = new byte[strArr.Length];
|
||
//逐个字符变为16进制字节数据
|
||
for (int i = 0; i < strArr.Length; i++)
|
||
{
|
||
b[i] = Convert.ToByte(strArr[i].Trim(), 16);
|
||
}
|
||
|
||
//按照指定编码将字节数组变为字符串
|
||
return b;
|
||
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 记录日志信息
|
||
byte[] data { get; set; }
|
||
|
||
/// <summary>
|
||
/// 文件夹路径
|
||
/// </summary>
|
||
string path { get; set; }
|
||
/// <summary>
|
||
/// 文件路径
|
||
/// </summary>
|
||
string paths { get; set; }
|
||
/// <summary>
|
||
/// 记录信息对象
|
||
/// </summary>
|
||
RecordInfo info { get; set; }
|
||
/// <summary>
|
||
/// 打开的文件流对象
|
||
/// </summary>
|
||
FileStream FS { get; set; }
|
||
|
||
/// <summary>
|
||
/// 记录远程交互信息
|
||
/// </summary>
|
||
/// <param name="info"></param>
|
||
private void RecordRemoteSensingLog(string showMag)
|
||
{
|
||
info = new RecordInfo() { Number = 1, HappenTime = DateTime.Now, Describe = showMag };
|
||
try
|
||
{
|
||
path = @"E:\\RemoteSensingLog";
|
||
paths = @"E:\\RemoteSensingLog\" + DateTime.Now.ToString("D") + ".txt";
|
||
//创建文件夹
|
||
if (!Directory.Exists(path))
|
||
{
|
||
Directory.CreateDirectory(path);
|
||
}
|
||
|
||
//打开或创建文件
|
||
FS = File.Open(paths, FileMode.Append);
|
||
|
||
//获得字节数组
|
||
|
||
data = System.Text.Encoding.Default.GetBytes(info.Number + "-" + info.HappenTime + "-" + info.Describe + "\r\n");
|
||
//开始写入
|
||
FS.Write(data, 0, data.Length);
|
||
//清空缓冲区、关闭流
|
||
FS.Flush();
|
||
FS.Close();
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
}
|