712 lines
21 KiB
C#
712 lines
21 KiB
C#
using Community;
|
||
using MahApps.Metro.Controls;
|
||
using Model;
|
||
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.Collections.ObjectModel;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Net.NetworkInformation;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using System.Windows;
|
||
using System.Windows.Threading;
|
||
using DAL;
|
||
using System.IO;
|
||
|
||
namespace ViewModel
|
||
{
|
||
/// <summary>
|
||
/// 通讯服务器管理逻辑类
|
||
/// </summary>
|
||
public class CommunicationServerVM : NotificationObject
|
||
{
|
||
/// <summary>
|
||
/// 系统软件ID
|
||
/// </summary>
|
||
int SoftID { get; set; }
|
||
|
||
/// <summary>
|
||
/// 自动获取端口号
|
||
/// </summary>
|
||
public DelegateCommand GetPortCommand { get; set; }
|
||
|
||
/// <summary>
|
||
/// 添加
|
||
/// </summary>
|
||
public DelegateCommand AddTCPIPCommand { get; set; }
|
||
|
||
/// <summary>
|
||
/// 删除
|
||
/// </summary>
|
||
public DelegateCommand DeleteTCPIPCommand { get; set; }
|
||
|
||
/// <summary>
|
||
/// 保存TCPIP参数
|
||
/// </summary>
|
||
public DelegateCommand SaveParCommand { get; set; }
|
||
|
||
/// <summary>
|
||
/// 发送信息方法
|
||
/// </summary>
|
||
public DelegateCommand SendInfoCommand { get; set; }
|
||
|
||
|
||
/// <summary>
|
||
/// 连接监听套接字
|
||
/// </summary>
|
||
public Socket SocketListen { get; set; }
|
||
|
||
private ShowInfo showmsg;
|
||
/// <summary>
|
||
/// 监听连接状态
|
||
/// </summary>
|
||
public ShowInfo Showmsg
|
||
{
|
||
get { return showmsg; }
|
||
set
|
||
{
|
||
showmsg = value;
|
||
this.RaisePropertyChanged("Showmsg");
|
||
}
|
||
}
|
||
|
||
#region 监听开关
|
||
private bool monitorsWitch;
|
||
/// <summary>
|
||
/// 监听开关
|
||
/// </summary>
|
||
public bool MonitorsWitch
|
||
{
|
||
get { return monitorsWitch; }
|
||
set
|
||
{
|
||
monitorsWitch = value;
|
||
if (value)
|
||
{
|
||
// StartListen();
|
||
StartListen();
|
||
}
|
||
else
|
||
{
|
||
EndListen();
|
||
}
|
||
this.RaisePropertyChanged("MonitorsWitch");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region TCPIP通讯连接参数
|
||
private TCPIPClass serverConn;
|
||
/// <summary>
|
||
/// TCPIP通讯连接参数
|
||
/// </summary>
|
||
public TCPIPClass ServerConn
|
||
{
|
||
get { return serverConn; }
|
||
set
|
||
{
|
||
serverConn = value;
|
||
this.RaisePropertyChanged("ServerConn");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 已连接通讯对象集合
|
||
private ObservableCollection<CommunicationManagementClass> commList;
|
||
/// <summary>
|
||
/// 已连接对象集合
|
||
/// </summary>
|
||
public ObservableCollection<CommunicationManagementClass> CommList
|
||
{
|
||
get { return commList; }
|
||
set
|
||
{
|
||
commList = value;
|
||
//this.RaisePropertyChanged("ConnectionClassList");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 当前选中的通讯对象
|
||
private CommunicationManagementClass selectComm;
|
||
/// <summary>
|
||
/// 当前选中的通讯对象
|
||
/// </summary>
|
||
public CommunicationManagementClass SelectComm
|
||
{
|
||
get { return selectComm; }
|
||
set
|
||
{
|
||
selectComm = value;
|
||
this.RaisePropertyChanged("SelectComm");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
|
||
|
||
#region 构造函数
|
||
/// <summary>
|
||
/// 构造函数
|
||
/// </summary>
|
||
/// <param name="ip"></param>
|
||
/// <param name="port"></param>
|
||
public CommunicationServerVM(string ip, int port)
|
||
{
|
||
//IP= GetIP(); //获取IP地址 因为无法获取指定网卡的IP 此处不用
|
||
ServerConn.IP = ip;
|
||
ServerConn.Port = port; //端口号随便来
|
||
Showmsg = new ShowInfo();
|
||
CommList = new ObservableCollection<CommunicationManagementClass>();
|
||
}
|
||
|
||
|
||
MainWindowDAL dal = new MainWindowDAL();
|
||
/// <summary>
|
||
/// 程序主线程队列 用于异步属性界面
|
||
/// </summary>
|
||
Dispatcher MyDispatcher { get; set; }
|
||
/// <summary>
|
||
/// 构造函数重载
|
||
/// </summary>
|
||
/// <param name="softID">系统软件ID</param>
|
||
/// <param name="dp">窗体对象,用于动态添加项</param>
|
||
public CommunicationServerVM(int softID, Dispatcher dp)
|
||
{
|
||
MyDispatcher = dp;
|
||
PLCConn = new CommunicationManagementClass();
|
||
FrontStation = new CommunicationManagementClass();
|
||
|
||
SoftID = softID;
|
||
ServerConn = dal.GetTCPIPServer(SoftID);//new TCPIPClass();
|
||
|
||
|
||
CommList = dal.GetCommClientList1(SoftID);
|
||
if (CommList.Count > 0)
|
||
{
|
||
CommList.Insert(0, new CommunicationManagementClass() { ActionName = " ", ID = -1 });
|
||
SelectComm = CommList[1];
|
||
}
|
||
Showmsg = new ShowInfo();
|
||
|
||
GetPortCommand = new DelegateCommand();
|
||
GetPortCommand.ExecuteAction = new Action<object>(GetPort);
|
||
|
||
SaveParCommand = new DelegateCommand();
|
||
SaveParCommand.ExecuteAction = new Action<object>(SavePar);
|
||
|
||
SendInfoCommand = new DelegateCommand();
|
||
SendInfoCommand.ExecuteAction = new Action<object>(SendInfo);
|
||
|
||
AddTCPIPCommand = new DelegateCommand();
|
||
AddTCPIPCommand.ExecuteAction = new Action<object>(AddTCPIP);
|
||
|
||
DeleteTCPIPCommand = new DelegateCommand();
|
||
DeleteTCPIPCommand.ExecuteAction = new Action<object>(DeleteTCPIP);
|
||
|
||
|
||
}
|
||
#endregion
|
||
|
||
#region 1、获取本地IP string GetIP()
|
||
/// <summary>
|
||
/// 获取本地IP
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
private string GetIP() //获取本地IP
|
||
{
|
||
string ip = string.Empty;
|
||
foreach (IPAddress ipadd in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
|
||
{
|
||
|
||
if (ipadd.AddressFamily.ToString() == "InterNetwork")
|
||
{
|
||
ip = ipadd.ToString();
|
||
break;
|
||
}
|
||
}
|
||
return ip;
|
||
}
|
||
#endregion
|
||
|
||
#region 2、获取可使用端口 int GetPort()
|
||
/// <summary>
|
||
/// 获取可使用端口
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
private void GetPort(object obj)
|
||
{
|
||
int max_port = 65535; //系统tcp/udp端口数最大是65535
|
||
int begin_port = 5000;//从这个端口开始检测
|
||
int port = 0;
|
||
for (int i = begin_port; i < max_port; i++)
|
||
{
|
||
if (PortIsAvailable(i))
|
||
{
|
||
port = i;
|
||
break;
|
||
}
|
||
}
|
||
ServerConn.Port = port;
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// 检查指定端是否已占用
|
||
/// </summary>
|
||
/// <param name="port"></param>
|
||
/// <returns></returns>
|
||
private static bool PortIsAvailable(int port)
|
||
{
|
||
bool isAvailable = true;
|
||
|
||
IList portUsed = PortIsUsed();
|
||
|
||
foreach (int p in portUsed)
|
||
{
|
||
if (p == port)
|
||
{
|
||
isAvailable = false; break;
|
||
}
|
||
}
|
||
|
||
return isAvailable;
|
||
}
|
||
|
||
|
||
|
||
/// <summary>
|
||
/// 获取操作系统已用的端口号
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public static IList PortIsUsed()
|
||
{
|
||
//获取本地计算机的网络连接和通信统计数据的信息
|
||
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
|
||
|
||
//返回本地计算机上的所有Tcp监听程序
|
||
IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners();
|
||
|
||
//返回本地计算机上的所有UDP监听程序
|
||
IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners();
|
||
|
||
//返回本地计算机上的Internet协议版本4(IPV4 传输控制协议(TCP)连接的信息。
|
||
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
|
||
|
||
IList allPorts = new ArrayList();
|
||
foreach (IPEndPoint ep in ipsTCP) allPorts.Add(ep.Port);
|
||
foreach (IPEndPoint ep in ipsUDP) allPorts.Add(ep.Port);
|
||
foreach (TcpConnectionInformation conn in tcpConnInfoArray) allPorts.Add(conn.LocalEndPoint.Port);
|
||
|
||
return allPorts;
|
||
}
|
||
#endregion
|
||
|
||
#region 3、循环接受客户端连接的方法
|
||
|
||
#region 临时通讯对象
|
||
/// <summary>
|
||
/// 临时通讯对象
|
||
/// </summary>
|
||
public CommunicationManagementClass TempConn { get; set; }
|
||
|
||
#endregion
|
||
|
||
#region 各通讯连接对象
|
||
|
||
#region PLC连接
|
||
private CommunicationManagementClass pLCConn;
|
||
/// <summary>
|
||
/// PLC连接
|
||
/// </summary>
|
||
public CommunicationManagementClass PLCConn
|
||
{
|
||
get { return pLCConn; }
|
||
set
|
||
{
|
||
pLCConn = value;
|
||
this.RaisePropertyChanged("PLCConn");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 测试站PC连接1
|
||
private CommunicationManagementClass frontStation;
|
||
/// <summary>
|
||
/// 上一站连接
|
||
/// </summary>
|
||
public CommunicationManagementClass FrontStation
|
||
{
|
||
get { return frontStation; }
|
||
set
|
||
{
|
||
frontStation = value;
|
||
this.RaisePropertyChanged("FrontStation");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
|
||
|
||
#endregion
|
||
|
||
|
||
#region 1、开启监听
|
||
/// <summary>
|
||
/// 开启监听
|
||
/// </summary>
|
||
private void StartListen()
|
||
{
|
||
try
|
||
{
|
||
Socket SocketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||
SocketListen.Bind(new IPEndPoint(IPAddress.Parse(ServerConn.IP), ServerConn.Port));
|
||
SocketListen.Listen(10);//同时连接的最大连接数
|
||
SocketListen.BeginAccept(new AsyncCallback(ClientAccepted), SocketListen);//获取连接
|
||
|
||
Showmsg.StatuInfo = "通讯服务正常";
|
||
Showmsg.StatusBackground = ColorStr.Green;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Showmsg.StatuInfo = ex.Message;
|
||
Showmsg.StatusBackground = ColorStr.Red;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
if (SocketListen != null)
|
||
{
|
||
SocketListen.Close();
|
||
SocketListen = null;
|
||
}
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 2、异步连接回调 获取请求Socket
|
||
/// <summary>
|
||
/// 接收到的字节
|
||
/// </summary>
|
||
byte[] buffer = new byte[1024 * 1024 * 1];
|
||
/// <summary>
|
||
/// 异步连接回调 获取请求Socket
|
||
/// </summary>
|
||
/// <param name="ar">请求的Socket</param>
|
||
private void ClientAccepted(IAsyncResult ar)
|
||
{
|
||
try
|
||
{
|
||
//获取连接Socket 创建新的连接
|
||
Socket myServer = ar.AsyncState as Socket;
|
||
Socket client = myServer.EndAccept(ar);
|
||
|
||
IPAddress ip = ((System.Net.IPEndPoint)client.RemoteEndPoint).Address;
|
||
string ClientName = "";
|
||
|
||
|
||
ClientName = ip.ToString();
|
||
|
||
if (!string.IsNullOrEmpty(ClientName))
|
||
{
|
||
if (!RestartConn(ClientName, client, ClientName))
|
||
{
|
||
TempConn = new CommunicationManagementClass(client, ClientName, ClientName);
|
||
//异步新增项 这是微软的BUG 只能这么麻烦了
|
||
MyDispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), TempConn);
|
||
//这样写也可以 MyMessageBox.MetroWin.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), TempConn);
|
||
SelectComm = TempConn;
|
||
|
||
}
|
||
}
|
||
else
|
||
{
|
||
//异步识别验证连接者身份验证
|
||
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), client);
|
||
}
|
||
|
||
|
||
//异步识别验证连接者身份验证
|
||
// client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), client);
|
||
myServer.BeginAccept(new AsyncCallback(ClientAccepted), myServer);//等待下一个连接
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Showmsg.StatuInfo = ex.Message;
|
||
Showmsg.StatusBackground = ColorStr.Red;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 3、数据接收 进行身份识别
|
||
/// <summary>
|
||
/// 数据接收 进行身份识别
|
||
/// </summary>
|
||
/// <param name="ar">请求的Socket</param>
|
||
private void ReadCallback(IAsyncResult ar)
|
||
{
|
||
Socket c_socket = ar.AsyncState as Socket;
|
||
|
||
#region 这里是特殊情况 用IP地址来识别身份
|
||
IPAddress ip = ((System.Net.IPEndPoint)c_socket.RemoteEndPoint).Address;
|
||
string ClientName = "";
|
||
switch (ip.ToString())
|
||
{
|
||
case "192.168.20.1":
|
||
//ClientName = "C1";
|
||
break;
|
||
case "192.168.3.10":
|
||
//ClientName = "PL";
|
||
break;
|
||
default:
|
||
try
|
||
{
|
||
int length = c_socket.EndReceive(ar);
|
||
ClientName = Encoding.UTF8.GetString(buffer, 0, length);
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
break;
|
||
}
|
||
if (!RestartConn(ClientName, c_socket))
|
||
{
|
||
switch (ClientName)
|
||
{
|
||
case "PL":
|
||
TempConn = new CommunicationManagementClass(c_socket, ClientName, "PLC连接");
|
||
//异步新增项 这是微软的BUG 只能这么麻烦了
|
||
MyDispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), TempConn);
|
||
SelectComm = TempConn;
|
||
PLCConn = TempConn;
|
||
break;
|
||
case "SL":
|
||
TempConn = new CommunicationManagementClass(c_socket, ClientName, "上一站");
|
||
//异步新增项 这是微软的BUG 只能这么麻烦了
|
||
MyDispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), TempConn);
|
||
FrontStation = TempConn;
|
||
SelectComm = TempConn;
|
||
break;
|
||
|
||
}
|
||
|
||
}
|
||
|
||
#endregion
|
||
|
||
}
|
||
|
||
void AddItem(object info)
|
||
{
|
||
CommList.Add((CommunicationManagementClass)info);
|
||
}
|
||
#endregion
|
||
|
||
#region 4、查看是否已连接,如果已连接 就重启接收信息
|
||
/// <summary>
|
||
/// 查看是否已连接,如果已连接 就重启接收信息
|
||
/// </summary>
|
||
/// <param name="userName">用户对象</param>
|
||
/// <returns></returns>
|
||
public bool RestartConn(string userName, Socket currSocket, string nameStr = "")
|
||
{
|
||
bool CheckConnAre = false;
|
||
|
||
if (CommList == null || CommList.Count <= 0)
|
||
{
|
||
return CheckConnAre;
|
||
}
|
||
|
||
foreach (CommunicationManagementClass cl in CommList)
|
||
{
|
||
if (cl.ShortCode == userName)
|
||
{
|
||
CheckConnAre = true;
|
||
//重新开启此连接
|
||
cl.ConnSocket = currSocket; //替换新的通信套接字
|
||
cl.OpenReceivesMassage();
|
||
cl.Names = nameStr;//cl.TempName;
|
||
cl.Showmsg.StatuInfo = "连接正常";
|
||
cl.Showmsg.StatusBackground = ColorStr.Green;
|
||
cl.Showmsg.StatusForeground = ColorStr.White;
|
||
SelectComm = cl;
|
||
break;
|
||
}
|
||
}
|
||
|
||
return CheckConnAre;
|
||
}
|
||
#endregion
|
||
|
||
|
||
#endregion
|
||
|
||
#region 4、关闭连接
|
||
/// <summary>
|
||
/// 关闭连接
|
||
/// </summary>
|
||
public void EndListen()
|
||
{
|
||
try
|
||
{
|
||
SocketListen.Close();
|
||
SocketListen = null;
|
||
Showmsg.StatuInfo = "未启动";
|
||
Showmsg.StatusBackground = ColorStr.Red;
|
||
Showmsg.StatusForeground = ColorStr.White;
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 5、更新TCPIP参数
|
||
/// <summary>
|
||
/// 5、更新TCPIP参数
|
||
/// </summary>
|
||
/// <param name="obj"></param>
|
||
private void SavePar(object obj)
|
||
{
|
||
if (dal.TCPUpdata(this.ServerConn) <= 0)
|
||
{
|
||
MyMessageBox.Show("服务器参数保存失败");
|
||
}
|
||
|
||
if (SelectComm != null && SelectComm.ID >= 0)
|
||
{
|
||
if (dal.SaveTCPIPPar(SelectComm) > 0)
|
||
{
|
||
MyMessageBox.Show("保存成功");
|
||
}
|
||
else
|
||
{
|
||
MyMessageBox.Show("保存失败");
|
||
}
|
||
}
|
||
|
||
|
||
}
|
||
#endregion
|
||
|
||
#region 6、删除TCPIP
|
||
/// <summary>
|
||
/// 删除TCPIP
|
||
/// </summary>
|
||
/// <param name="obj"></param>
|
||
private void DeleteTCPIP(object obj)
|
||
{
|
||
if (SelectComm == null || SelectComm.ID < 0)
|
||
{
|
||
return;
|
||
}
|
||
|
||
if (SelectComm.ID > 0)
|
||
{
|
||
if (dal.DelectTcpIP(SelectComm.ID) <= 0)
|
||
{
|
||
MyMessageBox.Show("删除失败");
|
||
}
|
||
else
|
||
{
|
||
CommList.Remove(SelectComm);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
CommList.Remove(SelectComm);
|
||
}
|
||
|
||
}
|
||
#endregion
|
||
|
||
#region 7、新增TCPIP
|
||
/// <summary>
|
||
/// 新增TCPIP
|
||
/// </summary>
|
||
/// <param name="obj"></param>
|
||
private void AddTCPIP(object obj)
|
||
{
|
||
CommunicationManagementClass cmc = new CommunicationManagementClass() { SoftID = this.SoftID, ActionName = "新来的", InServer = false, IP = "127.0.0.1" };
|
||
CommList.Add(cmc);
|
||
SelectComm = cmc;
|
||
}
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 发送信息
|
||
/// </summary>
|
||
public void SendInfo(object obj)
|
||
{
|
||
if (SelectComm != null)
|
||
{
|
||
SelectComm.SendInfo(SelectComm.SendStr);
|
||
}
|
||
}
|
||
|
||
#region IP地址格式验证
|
||
/// <summary>
|
||
/// IP地址格式验证1
|
||
/// </summary>
|
||
/// <param name="IPstr"></param>
|
||
/// <returns></returns>
|
||
public bool IPCheck(string IPstr)
|
||
{
|
||
bool blnTest = false;
|
||
bool Result = true;
|
||
|
||
Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
|
||
blnTest = regex.IsMatch(IPstr);
|
||
if (blnTest == true)
|
||
{
|
||
string[] strTemp = IPstr.Split(new char[] { '.' }); // textBox1.Text.Split(new char[] { '.' });
|
||
for (int i = 0; i < strTemp.Length; i++)
|
||
{
|
||
if (Convert.ToInt32(strTemp[i]) > 255)
|
||
{ //大于255则提示,不符合IP格式
|
||
MessageBox.Show("不符合IP格式");
|
||
Result = false;
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
//输入非数字则提示,不符合IP格式
|
||
MessageBox.Show("不符合IP格式");
|
||
Result = false;
|
||
}
|
||
|
||
return Result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// IP地址格式验证2
|
||
/// </summary>
|
||
/// <param name="IpStr"></param>
|
||
/// <returns></returns>
|
||
private bool isIP(String IpStr)
|
||
{
|
||
bool IsIpResult = false;
|
||
try
|
||
{
|
||
IPAddress ipAd = IPAddress.Parse(IpStr);
|
||
IsIpResult = true;
|
||
}
|
||
catch
|
||
{
|
||
IsIpResult = false;
|
||
}
|
||
return IsIpResult;
|
||
}
|
||
#endregion
|
||
|
||
|
||
}
|
||
}
|