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
{
///
/// 通讯类
///
public class CommunicationManagementClass : NotificationObject
{
#region 基础参数
public int ID { get; set; }
///
/// 软件ID
///
public int SoftID { get; set; }
private string actionName;
///
/// 作用名称
///
public string ActionName
{
get { return actionName; }
set
{
actionName = value;
Names = value;
TempName = value;
this.RaisePropertyChanged("ActionName");
}
}
///
/// 简码 用于发给服务器进行身份识别
///
public string ShortCode { get; set; }
///
/// 主动发送身份识别码
///
public bool SendShortCode { get; set; }
#region IP
private string ip;
///
/// IP地址
///
public string IP
{
get { return ip; }
set
{
ip = value;
this.RaisePropertyChanged("IP");
}
}
#endregion
#region Port端口号
private int port;
///
/// Port端口号
///
public int Port
{
get { return port; }
set
{
port = value;
this.RaisePropertyChanged("Port");
}
}
#endregion
///
/// 是否为服务器通讯连接
///
public bool InServer { get; set; }
private bool activeConnection;
///
/// 主动连接
///
public bool ActiveConnection
{
get { return activeConnection; }
set
{
activeConnection = value;
ConnButtonShow = value ? Visibility.Visible : Visibility.Collapsed;
this.RaisePropertyChanged("ActiveConnection");
}
}
private Visibility connButtonShow;
///
/// 是否显示连接按钮
///
public Visibility ConnButtonShow
{
get { return connButtonShow; }
set
{
connButtonShow = value;
this.RaisePropertyChanged("ConnButtonShow");
}
}
///
/// 通过端口号识别身份,但此字段为True时,Ip与Port需一致 从而确认客户端身份
///
public bool PortDis { get; set; }
private bool redeive16;
///
/// 是否16进制接收
///
public bool Redeive16
{
get { return redeive16; }
set
{
redeive16 = value;
this.RaisePropertyChanged("Redeive16");
}
}
private bool send16;
///
/// 是否是16进制发送
///
public bool Send16
{
get { return send16; }
set
{
send16 = value;
this.RaisePropertyChanged("Send16");
}
}
#endregion
///
/// 消息状态委托
///
public delegate void delegateReceivePower(string str);
///
/// 消息传递时间
///
public event delegateReceivePower ReceiveCallback;
///
/// 通信套接字
///
public Socket ConnSocket { get; set; }
#region 发送的字符串内容
private string sendStr;
///
/// 发送的字符串内容
///
public string SendStr
{
get { return sendStr; }
set
{
sendStr = value;
this.RaisePropertyChanged("SendStr");
}
}
#endregion
#region 接收到的字符串信息
private string receiveInfo;
///
/// 接收到的字符串信息
///
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;
///
/// 连接开关
///
public bool ConnectSwitch
{
get { return connectSwitch; }
set
{
connectSwitch = value;
ReconnectSwitch = false;
this.RaisePropertyChanged("ConnectSwitch");
if (value && this.ActiveConnection)
{
OpenConn();
}
else
{
CloseConn();
}
}
}
///
/// 是否需要重新连接
///
///
public bool ReconnectSwitch { get; set; }
#endregion
#region 连接状态
private ShowInfo showmsg;
///
/// 连接状态
///
public ShowInfo Showmsg
{
get { return showmsg; }
set
{
showmsg = value;
this.RaisePropertyChanged("Showmsg");
}
}
#endregion
#region 连接对象名称
private string names;
///
/// 连接对象名称
///
public string Names
{
get { return names; }
set
{
names = value;
this.RaisePropertyChanged("Names");
}
}
#endregion
#region 构造函数
///
/// 构造函数
///
/// IP地址
/// 端口号
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 = "";
///
/// 构造函数的重载
///
/// 连接过来的客户端对象
/// 客户端通信套接字
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;
}
///
/// 无参构造函数
///
public CommunicationManagementClass()
{
Showmsg = new ShowInfo();
Showmsg.StatuInfo = "等待连接";
Showmsg.StatusBackground = ColorStr.Gray;
Showmsg.StatusForeground = ColorStr.White;
ConnButtonShow = Visibility.Collapsed;
this.InServer = false;
}
#endregion
#region 开启数据接收
///
/// 开启数据接收
///
public void OpenReceivesMassage()
{
ConnSocket.BeginReceive(Buffes, 0, Buffes.Length, 0, new AsyncCallback(ReadCallback), ConnSocket);
}
///
/// 接收到的字节
///
public byte[] Buffes = new byte[1024 * 1024 * 5];
///
/// 数据接收
///
/// 请求的Socket
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;
///
/// 开启连接
///
public void OpenConn()
{
try
{
if (ConnSocket == null)
{
//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;
}
}
///
/// 异步连接
///
///
private void ConnectCallback(IAsyncResult ar)
{
try
{
//allDone.Set();
// ConnSocket = (Socket)ar.AsyncState;
if (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;
//重连
ConnSocket.BeginConnect(Endpoint, new AsyncCallback(ConnectCallback), ConnSocket);
}
}
catch
{
//重新连接
ReconnectSwitch = true;
}
}
#endregion
#region 关闭连接
///
/// 关闭连接
///
public void CloseConn()
{
try
{
if (ConnSocket != null)
{
ConnSocket.Close(); //关闭套接字
ConnSocket = null;
Showmsg.StatuInfo = "未连接!";
Showmsg.StatusBackground = ColorStr.Red;
Showmsg.StatusForeground = ColorStr.White;
}
}
catch
{
}
}
#endregion
#region 发送消息
///
/// 发送消息
///
/// 发送内容
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();
}
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进制
///
/// 字符串转16进制
///
///
///
private byte[] StringToBytes(string str)
{
try //尝试将发送的数据转为16进制Hex
{
str = StringToHex(str.Trim());
return HexToBytes(str);
}
catch //无法转为16进制时,出现异常
{
return null;
}
}
///
/// string转Hex
///
///
///
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;
}
///
/// hex转string
///
///
///
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);
}
///
/// hex转byte[]
///
///
///
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], 16);
}
//按照指定编码将字节数组变为字符串
return b;
}
#endregion
#region 记录日志信息
byte[] data { get; set; }
///
/// 文件夹路径
///
string path { get; set; }
///
/// 文件路径
///
string paths { get; set; }
///
/// 记录信息对象
///
RecordInfo info { get; set; }
///
/// 打开的文件流对象
///
FileStream FS { get; set; }
///
/// 记录远程交互信息
///
///
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
}
}