using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
namespace SimpleCommunication
{
public partial class CommunUI : UserControl
{
///
/// 保存委托
///
///
///
public delegate void SaveParamsHandler(int plcIndex, int trgIndex);
public event SaveParamsHandler SaveParamsEvent;
///
/// 通讯接收数据委托
///
///
public delegate void TCPCOMRecvMsgHandle(StringBox msgBox);
public TCPCOMRecvMsgHandle TcoComRecvMsgEvent;
///
/// 常规数据信息委托
///
///
public delegate void TCPCOMInfoMsgHandle(StringBox msgBox);
public TCPCOMInfoMsgHandle TcoComInfoMsgEvent;
///
/// 串口
///
public Serial comSerial;
///
/// TCP服务端
///
public Server tcpServer;
///
/// TCP客户端
///
public Client tcpClient;
///
/// Com通讯类型
///
public bool com;
///
/// TCP服务端类型
///
public bool server;
///
/// TCP客户端类型
///
public bool client;
///
/// 服务端创建事件成功
///
public bool ServerCreatedSuccessfully = false;
///
///客户端创建事件成功
///
public bool ClientCreatedSuccessfully = false;
///
/// 串口端创建事件成功
///
public bool comSerialCreatedSuccessfully = false;
///
/// 结束符号
///
public string Endsymbol;
///
/// 是否链接成功
///
public bool IsConnected => (com || server || client) ? true : false;
///
/// 通讯类型
///
public int type { get; private set; }
///
/// 选择服务端,选择Combox类型0
///
private bool isServer => tcpType_Box.SelectedIndex == 1;
public int JobCount { get; set; }
///
/// 发送次数
///
public int SendCount = 0;
///
/// 接收次数
///
public int RecvCount = 0;
///
/// 参数
///
public ComConfig ComConfig = new ComConfig();
///
/// 页面
///
public TabPage[] tgrPage = new TabPage[10];
public int Index;
public bool receiveHexShow;
public bool SendHexShow;
///
/// 构造函数
///
public CommunUI()
{
InitializeComponent();
comSerial = new Serial();
tcpServer = new Server();
tcpClient = new Client();
LocalIP(tbIP);
comSerial.LoadComSerial(comPort_Box);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
}
public CommunUI(ComConfig comConfig)
: this()
{
ComConfig = comConfig;
Index = ComConfig.Index;
JobCount = ComConfig.JobCount;
txtHeartData.Text = ComConfig.HeartText;
txtIntervalTime.Text = ComConfig.HeartTime.ToString();
tcpType_Box.SelectedIndex = ComConfig.Connect_Typt;
tbPort.Text = ComConfig.TCP_Port.ToString();
baudRate_Box.Text = ComConfig.COM_BaudRate.ToString();
parity_Box.Text = ComConfig.COM_Parity.ToString();
dataBits_Box.Text = ComConfig.COM_DataBit.ToString();
stopBits_Box.Text = ComConfig.COM_StopBit.ToString();
cmbEndSymbol.SelectedIndex = ComConfig.Endsymbol;
if (ComConfig.Connect_Typt == 0)//串口
{
//type = 0;
server = false;
client = false;
com = true;
ServerDlgSubscribe(0, true);
comSerialCreatedSuccessfully = true;
}
else if (ComConfig.Connect_Typt == 1) //服务器
{
//type = 1;
server = true;
client = false;
com = false;
btnStart.Text = "启动服务器";
btnDisconnect.Text = "关闭链接";
btnClose.Enabled = true;
ServerDlgSubscribe(1, true);
ServerCreatedSuccessfully = true;
}
else if (ComConfig.Connect_Typt == 2) //客户端
{
//type = 2;
server = false;
client = true;
com = false;
btnStart.Text = "链接服务";
btnDisconnect.Text = "断开链接";
btnClose.Enabled = false;
ServerDlgSubscribe(2, true);
ClientCreatedSuccessfully = true;
}
else
{
server = true;
com = true;
ServerDlgSubscribe(0, true);
comSerialCreatedSuccessfully = true;
btnStart.Text = "链接服务";
btnDisconnect.Text = "断开链接";
btnClose.Enabled = false;
ServerDlgSubscribe(2, true);
ClientCreatedSuccessfully = true;
}
}
#region 界面事件处理
///
/// 界面Loadsh
///
///
///
private void CommunUI_Load(object sender, EventArgs e)
{
}
private void com_Btn_Click(object sender, EventArgs e)
{
COMOpen();
}
public void COMOpen()
{
if (!comSerial.IsOpen)
{
StopBits stopBits = StopBits.None;
string text = stopBits_Box.Text;
if (!(text == "1"))
{
if (text == "2")
{
stopBits = StopBits.Two;
}
}
else
{
stopBits = StopBits.One;
}
if (comPort_Box.Text != "")
{
comSerial.OpenSerialPort(comPort_Box.Text, int.Parse(baudRate_Box.SelectedItem.ToString()), (Parity)parity_Box.SelectedIndex, int.Parse(dataBits_Box.SelectedItem.ToString()), stopBits);
Thread.Sleep(50);
if (comSerial.IsOpen)
{
if (!comSerialCreatedSuccessfully)
{
ServerDlgSubscribe(2, true);
comSerialCreatedSuccessfully = true;
}
//LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", comSerial.getUserPortName(), " <--> 串口已打开!\r\n"));
info_Lab.Text = "串口:" + comSerial.getUserPortName();
info_Lab.BackColor = Color.Green;
tcpBtn_Panel.Enabled = false;
com_Btn.Text = "关闭串口";
com_Btn.BackColor = Color.Green;
com_GroupBox.Enabled = false;
tcp_GroupBox.Enabled = false;
tcpType_Box.Enabled = false;
saveSetting_Btn.Enabled = true;
Auto_CheckBox.Enabled = true;
pgeAuto_CheckBox.Enabled = true;
}
}
else
{
MessageBox.Show("打开串口失败,无法获取串口!");
}
}
else
{
comSerial.CloseSeriaPort();
Thread.Sleep(50);
if (!comSerial.IsOpen)
{
if (comSerialCreatedSuccessfully)
{
ServerDlgSubscribe(2, false);
comSerialCreatedSuccessfully = false;
}
info_Lab.Text = "未连接";
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
tcpBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
com_Btn.Text = "打开串口";
com_Btn.BackColor = Color.Transparent;
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
tcpType_Box.Enabled = true;
//com = false;
}
}
}
///
/// 开启服务器链接
///
///
///
public void btnStart_Click(object sender, EventArgs e)
{
TCPOpen();
}
public void TCPOpen()
{
if (isServer)
{
//if (tcpServer.IsConnected)
//{
// try
// {
// tcpServer.DisconnectClient();
// }
// catch
// {
// }
// LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", tcpServer.listener.Server.LocalEndPoint, " <--> 服务器已关闭!\r\n"));
// tcpServer.Dispose();
// Thread.Sleep(200);
// if (!tcpServer.IsConnected)
// {
// if (ServerCreatedSuccessfully)
// {
// ServerDlgSubscribe(0, false);
// ServerCreatedSuccessfully = false;
// }
// info_Lab.Text = "未连接";
// info_Lab.BackColor = Color.Red;
// btnStart.Text = "连接网口";
// btnStart.ForeColor = Color.Black;
// btnStart.BackColor = Color.Transparent;
// com_GroupBox.Enabled = true;
// tcp_GroupBox.Enabled = true;
// comBtn_Panel.Enabled = true;
// saveSetting_Btn.Enabled = false;
// Auto_CheckBox.Enabled = false;
// pgeAuto_CheckBox.Enabled = false;
// tcpType_Box.Enabled = false;
// //server = false;
// type = tcpType_Box.SelectedIndex;
// }
//}
//else
//{
tcpServer.Start(tbIP, tbPort);
Thread.Sleep(50);
if (tcpServer.IsConnected)
{
if (!ServerCreatedSuccessfully)
{
ServerDlgSubscribe(0, true);
ServerCreatedSuccessfully = true;
}
ModifyShowsByServerState(true);
Thread acceptClientThread = new Thread(BeginAcceptClient);
acceptClientThread.IsBackground = true;
acceptClientThread.Start();
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", tcpServer.listener.Server.LocalEndPoint, " <--> 服务器已打开!\r\n"));
info_Lab.Text = "服务器:" + tcpServer.listener.Server.LocalEndPoint.ToString();
info_Lab.BackColor = Color.Green;
btnStart.Text = "断开网口";
btnStart.ForeColor = Color.White;
btnStart.BackColor = Color.Green;
com_GroupBox.Enabled = false;
tcp_GroupBox.Enabled = false;
comBtn_Panel.Enabled = false;
saveSetting_Btn.Enabled = true;
Auto_CheckBox.Enabled = true;
pgeAuto_CheckBox.Enabled = true;
tcpType_Box.Enabled = false;
type = tcpType_Box.SelectedIndex;
}
}
else if (!tcpClient.IsConnected)
{
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
btnStart.Text = "连接网口";
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
comBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
tcpType_Box.Enabled = true;
tcpClient.Connect(tbIP, tbPort);
Thread.Sleep(20);
if (tcpClient.IsConnected)
{
if (!ClientCreatedSuccessfully)
{
ServerDlgSubscribe(2, true);
ClientCreatedSuccessfully = true;
}
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", tcpClient.tcpclient.Client.LocalEndPoint, " <--> 已连接服务器!\r\n"));
btnStart.Text = "断开网口";
btnStart.ForeColor = Color.White;
btnStart.BackColor = Color.Green;
info_Lab.Text = "客户端:" + tcpClient.tcpclient.Client.LocalEndPoint.ToString();
info_Lab.BackColor = Color.Green;
com_GroupBox.Enabled = false;
tcp_GroupBox.Enabled = false;
comBtn_Panel.Enabled = false;
saveSetting_Btn.Enabled = true;
Auto_CheckBox.Enabled = true;
pgeAuto_CheckBox.Enabled = true;
tcpType_Box.Enabled = false;
type = tcpType_Box.SelectedIndex;
}
}
else
{
try
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", tcpClient.tcpclient.Client.LocalEndPoint, " <--> 与服务器断开!\r\n"));
tcpClient.Dispose();
}
catch
{
}
Thread.Sleep(50);
if (ClientCreatedSuccessfully)
{
ServerDlgSubscribe(1, false);
ClientCreatedSuccessfully = false;
}
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
btnStart.Text = "连接网口";
btnStart.ForeColor = Color.Black;
btnStart.BackColor = Color.Transparent;
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
comBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
tcpType_Box.Enabled = false;
type = tcpType_Box.SelectedIndex;
}
}
private void tcpType_Box_SelectedIndexChanged(object sender, EventArgs e)
{
if (tcpType_Box.SelectedIndex > 0)
{
tbIP.DropDownStyle = ComboBoxStyle.DropDown;
}
else
{
tbIP.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
private void cmbEndSymbol_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cmbEndSymbol.SelectedIndex)
{
case 0://无
Endsymbol = string.Empty;
break;
case 1://CRLF(\r\n)
Endsymbol = "\r\n";
break;
case 2://LF(\n)
Endsymbol = "\n";
break;
default://CR(\r)
Endsymbol = "\r";
break;
}
}
///
/// 调用发送数据
///
///
///
public void SendResult(string str)
{
try
{
if (!sendTest_CheckBox.Checked && str != null)
{
if (com && !server && !client)
{
comSerial.SendString(str);
}
if (server && !com && !client && tcpServer != null)
{
tcpServer.SendMsg(str);
}
if (client && !com && !server)
{
tcpClient.SendMsg(str);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public string SendReturnResult(string str)
{
string text = "";
try
{
if (!sendTest_CheckBox.Checked && str != null)
{
if (com && !server && !client)
{
text = comSerial.SendReturnData(str);
}
if (server && !com && !client && tcpServer != null)
{
tcpServer.SendMsg(str);
}
if (client && !com && !server)
{
tcpClient.SendMsg(str);
}
}
}
catch (Exception ex)
{
throw ex;
}
return text;
}
private void tmHeart_Tick(object sender, EventArgs e)
{
int num = Convert.ToInt32(txtIntervalTime.Text);
if (num > 0)
{
tmHeart.Interval = Convert.ToInt32(txtIntervalTime.Text);
}
KeepAlive();
}
public void KeepAlive()
{
if (this.InvokeRequired)
{
BeginInvoke(new Action(KeepAlive));
}
else if (IsConnected && pgeAuto_CheckBox.Checked && txtHeartData.Text != "")
{
if (com && !server && !client)
{
comSerial.SendString(txtHeartData.Text);
}
if (server && !com && !client)
{
tcpServer.SendMsg(txtHeartData.Text);
}
if (client && !com && !server)
{
tcpClient.SendMsg(txtHeartData.Text);
}
}
}
///
/// 刷新网口
///
///
///
private void reloadtcp_Btn_Click(object sender, EventArgs e)
{
LocalIP(tbIP);
}
///
/// 刷新串口
///
///
///
private void reloadCOM_Btn_Click(object sender, EventArgs e)
{
comSerial.LoadComSerial(comPort_Box);
}
private void saveSetting_Btn_Click(object sender, EventArgs e)
{
try
{
ComConfig.Index = Index;
ComConfig.JobCount = JobCount;
ComConfig.TCP_IP = tbIP.Text.Trim();
ComConfig.TCP_Port = Convert.ToInt32(tbPort.Text.Trim());
ComConfig.HeartBeat = pgeAuto_CheckBox.Checked;
ComConfig.HeartText = txtHeartData.Text.Trim();
ComConfig.HeartTime = Convert.ToInt32(txtIntervalTime.Text.Trim());
ComConfig.COM_Port = comPort_Box.Text.Trim();
ComConfig.COM_BaudRate = Convert.ToInt32(baudRate_Box.Text.Trim());
ComConfig.COM_DataBit = Convert.ToInt32(dataBits_Box.Text.Trim());
ComConfig.COM_Parity = parity_Box.Text.Trim();
ComConfig.COM_StopBit = Convert.ToInt32(stopBits_Box.Text.Trim());
ComConfig.Endsymbol = cmbEndSymbol.SelectedIndex;
OnSaveParams(Index, 0);
LogRecord("保存参数成功");
}
catch (Exception ex)
{
//AddLog(lstRecv, 2, "保存参数失败" + ex.Message);
}
}
///
/// 保存信息委托事件
///
///
///
public void OnSaveParams(int plcIndex, int trgIndex)
{
if (this.SaveParamsEvent != null)
{
this.SaveParamsEvent(plcIndex, trgIndex);
}
}
public void btnClose_Click(object sender, EventArgs e)
{
if (isServer)
{
if (tcpServer.ServerClose())
{
ModifyShowsByServerState(false);
}
if (ServerCreatedSuccessfully)
{
ServerDlgSubscribe(0, false);
ServerCreatedSuccessfully = false;
}
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
btnStart.Text = "连接网口";
btnStart.ForeColor = Color.Black;
btnStart.BackColor = Color.Transparent;
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
comBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
tcpType_Box.Enabled = false;
tcpServer.DisconnectClient();
}
else
{
tcpClient.LocalClientClose();
ModifyShowsByServerState(false);
if (ClientCreatedSuccessfully)
{
ServerDlgSubscribe(1, false);
ClientCreatedSuccessfully = false;
}
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
btnStart.Text = "连接网口";
btnStart.ForeColor = Color.Black;
btnStart.BackColor = Color.Transparent;
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
comBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
tcpType_Box.Enabled = false;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
this.txtRecv.Clear();
}
private void btnSend_Click(object sender, EventArgs e)
{
SendCount++;
ShowCount(SendCount, true);
string msg = this.txtSend.Text.Trim();
if (!string.IsNullOrEmpty(msg))
{
if (com && !server && !client)
{
comSerial.SendString($"{msg}{Endsymbol}");
msg = DateTime.Now.ToString("HH:mm:ss") + " [本机] :\r\n" + msg + "\r\n";
this.txtSend.Clear();
AppendText($"串口{comSerial.getUserPortName()} --> {msg}");
}
if (server && !com && !client)
{
if (tcpServer.listener != null && tcpServer.currentClient.tcpclient.Connected)
{
tcpServer.SendMsg(msg + Endsymbol);
msg = DateTime.Now.ToString("HH:mm:ss") + " [本机] :\r\n" + msg + "\r\n";
this.txtSend.Clear();
AppendText($"服务端 --> {msg}");
}
else
{
msg = DateTime.Now.ToString("HH:mm:ss") + " [本机] :\r\n未链接客户端,无法发送消息!\r\n";
AppendText($"服务端 --> {msg}");
}
}
if (client && !com && !server)
{
tcpClient.SendMsg($"{msg}{Endsymbol}");
msg = DateTime.Now.ToString("HH:mm:ss ") + "本机 :\r\n" + msg + "\r\n";
this.txtSend.Text = string.Empty;
AppendText($"客户端 --> {msg}");
}
}
else
{
MessageBox.Show("数据为空!");
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (isServer)
{
tcpServer.DisconnectClient();
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
btnStart.Text = "连接网口";
btnStart.ForeColor = Color.Black;
btnStart.BackColor = Color.Transparent;
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
comBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
tcpType_Box.Enabled = true;
ServerDlgSubscribe(0, false);
}
else if (client)
{
tcpClient.Dispose();
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
btnStart.Text = "连接网口";
btnStart.ForeColor = Color.Black;
btnStart.BackColor = Color.Transparent;
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
comBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
tcpType_Box.Enabled = true;
ServerDlgSubscribe(1, false);
}
//else
//{
// comSerial.CloseSeriaPort();
// ServerDlgSubscribe(2, false);
//}
}
private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (isServer)
{
ServerDlgSubscribe(0, false);
}
else if (client)
{
ServerDlgSubscribe(1, false);
}
else
{
ServerDlgSubscribe(2, false);
}
}
private void ServerForm_Load(object sender, EventArgs e)
{
//ModifyShowsByServerState(false);
//ModifyShowsByClientState(false);
}
#endregion
#region 界面逻辑函数
///
/// 获取本地电脑IP地址
///
///
public void LocalIP(ComboBox ipStr)
{
ipStr.Items.Clear();
string hostName = Dns.GetHostName();
IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
IPAddress[] addressList = hostEntry.AddressList;
foreach (IPAddress iPAddress in addressList)
{
if (iPAddress.AddressFamily == AddressFamily.InterNetwork)
{
ipStr.Items.Add(iPAddress.ToString());
}
}
if (ipStr.Items.Count != 0)
{
ipStr.Text = ipStr.Items[0].ToString();
}
}
///
/// 根据监听状态修改界面显示
/// ServerForm_Load,点击启用服务器,关闭服务器按钮后调用
///
///
private void ModifyShowsByServerState(bool serverStart)
{
//this.btnStart.Enabled = !serverStart;
//this.btnClose.Enabled = serverStart;
}
///
/// 根据连接状态修改界面显示
/// ServerForm_Load,Server_NewClientEvent,Server_RemoteDisconnectEvent,Server_LocalDisconnectEvent调用到
///
///
private void ModifyShowsByClientState(bool clientConnect)
{
this.btnSend.Enabled = clientConnect;
this.btnDisconnect.Enabled = clientConnect;
}
private string splitSymbols = "\r\n\r\n";
///
/// 日志记录
///
///
private void LogRecord(string content)
{
this.txtLog.AppendText(content + splitSymbols);
}
private void ControlsChange(bool connect)
{
this.btnStart.Enabled = !connect;
this.btnDisconnect.Enabled = connect;
this.btnClear.Enabled = true;
this.btnSend.Enabled = connect;
if (connect)
{
this.Text = "客户端(已连接)";
}
else
{
this.Text = "客户端(未连接)";
}
}
///
/// 将收文或发文字符串处理后加入文本接收区
///
///
private void AppendText(string param)
{
int index1 = this.txtRecv.Text.Length;
int length1 = param.IndexOf("\r\n");
int index2 = index1 + length1 + 2;
int length2 = param.Length - length1 - 2;
this.txtRecv.AppendText(param);
this.txtRecv.Select(index1, length1);
this.txtRecv.SelectionColor = Color.Green;
this.txtRecv.Select(index2, length2);
this.txtRecv.SelectionColor = Color.Black;
this.txtRecv.Select(this.txtRecv.Text.Length, 0);
if (index1 > 1000)
{
txtRecv.Clear();
}
this.txtRecv.Focus();
}
///
/// 发送接收次数
///
///
///
public void ShowCount(int SendCount, bool sor)
{
this.Invoke((EventHandler)(delegate
{
if (sor)
{
lbl_sendNum.Text = SendCount.ToString();
}
else
{
lbl_receiveNum.Text = SendCount.ToString();
}
}));
}
///
/// 日志消息显示
///
///
private void OnInfoMsg(StringBox msgBox)
{
if (TcoComInfoMsgEvent != null)
{
TcoComInfoMsgEvent(msgBox);
}
}
///
/// 接收消息
///
///
private void OnRcvMsg(StringBox msgBox)
{
if (msgBox.str != "" && TcoComRecvMsgEvent != null)
{
TcoComRecvMsgEvent(msgBox);
}
}
#endregion
#region 业务逻辑处理
///
/// 监听启动之后,线程中启动连接接收
///
private void BeginAcceptClient()
{
tcpServer.BeginAcceptClient();
}
///
/// 在构造函数和ServerForm_FormClosing里调用
///
///
private void ServerDlgSubscribe(int tyepe, bool add)
{
switch (tyepe)
{
case 0://串口
if (add)
{
comSerial.ComOpenEvent += new DlgNoParam(Com_OpenSerialEvent);
comSerial.SendMsgEvent += new DlgOneParam(Com_SendMsgEvent);
comSerial.RecvMsgEvent += new DlgOneParam(Com_RecvMsgEvent);
comSerial.ComDisconnectEvent += new DlgNoParam(Com_ComDisconnectEvent);
}
else
{
comSerial.ComOpenEvent -= new DlgNoParam(Com_OpenSerialEvent);
comSerial.SendMsgEvent -= new DlgOneParam(Com_SendMsgEvent);
comSerial.RecvMsgEvent -= new DlgOneParam(Com_RecvMsgEvent);
comSerial.ComDisconnectEvent -= new DlgNoParam(Com_ComDisconnectEvent);
}
break;
case 1://服务端
if (add)
{
tcpServer.ServerStartEvent += new DlgNoParam(Server_ServerStartEvent);
tcpServer.ServerCloseEvent += new DlgNoParam(Server_ServerCloseEvent);
tcpServer.NewClientEvent += new DlgOneParam(Server_NewClientEvent);
tcpServer.RecvMsgEvent += new DlgOneParam(Server_RecvMsgEvent);
tcpServer.RemoteDisconnectEvent += new DlgOneParam(Server_RemoteDisconnectEvent);
tcpServer.LocalDisconnectEvent += new DlgNoParam(Server_LocalDisconnectEvent);
}
else
{
tcpServer.ServerStartEvent -= new DlgNoParam(Server_ServerStartEvent);
tcpServer.ServerCloseEvent -= new DlgNoParam(Server_ServerCloseEvent);
tcpServer.NewClientEvent -= new DlgOneParam(Server_NewClientEvent);
tcpServer.RecvMsgEvent -= new DlgOneParam(Server_RecvMsgEvent);
tcpServer.RemoteDisconnectEvent -= new DlgOneParam(Server_RemoteDisconnectEvent);
tcpServer.LocalDisconnectEvent -= new DlgNoParam(Server_LocalDisconnectEvent);
}
break;
case 2://客户端
if (add)
{
tcpClient.ConnectFailEvent += new DlgNoParam(Client_ConnectFailEvent);
tcpClient.NewClientEvent += new DlgOneParam(Client_NewClientEvent);
tcpClient.RecvMsgEvent += new DlgOneParam(Client_RecvMsgEvent);
tcpClient.RemoteDisconnectEvent += new DlgOneParam(Client_RemoteDisconnectEvent);
tcpClient.LocalDisconnectEvent += new DlgNoParam(Client_LocalDisconnectEvent);
}
else
{
tcpClient.ConnectFailEvent -= new DlgNoParam(Client_ConnectFailEvent);
tcpClient.NewClientEvent -= new DlgOneParam(Client_NewClientEvent);
tcpClient.RecvMsgEvent -= new DlgOneParam(Client_RecvMsgEvent);
tcpClient.RemoteDisconnectEvent -= new DlgOneParam(Client_RemoteDisconnectEvent);
tcpClient.LocalDisconnectEvent -= new DlgNoParam(Client_LocalDisconnectEvent);
}
break;
default:
break;
}
}
#endregion
#region 服务端下层事件处理
public void Server_ServerStartEvent()
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "服务器已启动..."));
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "服务器已启动..."));
}
stringBox.ID = "1";
stringBox.str = string.Concat(tcpServer.listener.Server.LocalEndPoint.ToString(),"<-->TCP服务器已启动...");
OnInfoMsg(stringBox);
}
public void Server_ServerCloseEvent()
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "服务器已关闭..."));
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "服务器已关闭..."));
}
stringBox.ID = "2";
stringBox.str = string.Concat(tcpServer.listener.Server.LocalEndPoint.ToString(), "<-->TCP服务器已关闭...");
OnInfoMsg(stringBox);
}
public void Server_NewClientEvent(string param)
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "接收到客户端连接: ",param));
ModifyShowsByClientState(true);
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "接收到客户端连接: ", param));
ModifyShowsByClientState(true);
}
stringBox.ID = "1";
stringBox.str = string.Concat("接收到客户端连接: ", param);
OnInfoMsg(stringBox);
}
public void Server_RecvMsgEvent(string param)
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
AppendText(param);
}));
}
else
{
AppendText(param);
}
stringBox.str = param;
OnRcvMsg(stringBox);
}
public void Server_RemoteDisconnectEvent(string param)
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "远程客户端断开连接: ", param));
ModifyShowsByClientState(false);
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "远程客户端断开连接: ", param));
ModifyShowsByClientState(false);
}
stringBox.ID = "2";
stringBox.str = string.Concat("远程客户端断开连接: ", param);
OnInfoMsg(stringBox);
}
public void Server_LocalDisconnectEvent()
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "本地主动关闭远程客户端连接"));
ModifyShowsByClientState(false);
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "本地主动关闭远程客户端连接"));
ModifyShowsByClientState(false);
}
stringBox.ID = "2";
stringBox.str = string.Concat("本地主动关闭远程客户端连接");
OnInfoMsg(stringBox);
}
#endregion
#region 客户端下层事件处理
public void Client_ConnectFailEvent()
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "无法连接上指定服务器"));
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "无法连接上指定服务器"));
}
stringBox.ID = "2";
stringBox.str = string.Concat("本地客户端无法连接上指定服务器");
OnInfoMsg(stringBox);
}
public void Client_NewClientEvent(string param)
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "链接:", param, " 服务端成功"));
ControlsChange(true);
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "链接:", param, " 服务端成功"));
ControlsChange(true);
}
stringBox.ID = "1";
stringBox.str = string.Concat("链接:", param, " 服务端成功");
OnInfoMsg(stringBox);
}
public void Client_RecvMsgEvent(string param)
{
if (!string.IsNullOrEmpty(param))
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new System.Threading.ThreadStart(delegate ()
{
AppendText(param);
}));
}
else
{
AppendText(param);
}
stringBox.str = param;
OnRcvMsg(stringBox);
}
}
public void Client_RemoteDisconnectEvent(string param)
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new System.Threading.ThreadStart(delegate ()
{
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
btnStart.Text = "连接网口";
btnStart.ForeColor = Color.Black;
btnStart.BackColor = Color.Transparent;
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
comBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
tcpType_Box.Enabled = true;
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n","服务端:" ,param," 关闭服务"));
ControlsChange(false);
}));
}
else
{
info_Lab.Text = "未连接";
info_Lab.BackColor = Color.Red;
btnStart.Text = "连接网口";
btnStart.ForeColor = Color.Black;
btnStart.BackColor = Color.Transparent;
com_GroupBox.Enabled = true;
tcp_GroupBox.Enabled = true;
comBtn_Panel.Enabled = true;
saveSetting_Btn.Enabled = false;
Auto_CheckBox.Enabled = false;
pgeAuto_CheckBox.Enabled = false;
tcpType_Box.Enabled = true;
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "服务端:", param, " 关闭服务"));
ControlsChange(false);
}
stringBox.ID = "2";
stringBox.str = string.Concat("服务端:", param, " 关闭服务");
OnInfoMsg(stringBox);
}
public void Client_LocalDisconnectEvent()
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new System.Threading.ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "本地客户端关闭服务"));
ControlsChange(false);
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", "本地客户端关闭服务"));
ControlsChange(false);
}
stringBox.ID = "2";
stringBox.str = string.Concat("本地客户端关闭服务");
OnInfoMsg(stringBox);
}
#endregion
#region 串口下层事件处理
///
/// 串口打开事件
///
public void Com_OpenSerialEvent()
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", comSerial.getUserPortName(), " <--> 串口已打开!\r\n"));
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", comSerial.getUserPortName(), " <--> 串口已打开!\r\n"));
}
stringBox.ID = "1";
stringBox.str = string.Concat(comSerial.getUserPortName(), " <--> 串口已打开!");
OnInfoMsg(stringBox);
}
///
/// 串口关闭事件
///
public void Com_ComDisconnectEvent()
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", comSerial.getUserPortName(), " <--> 串口已关闭!\r\n"));
}));
}
else
{
LogRecord(string.Concat("【", DateTime.Now.ToString("HH:mm:ss.fff"), "】\r\n", comSerial.getUserPortName(), " <--> 串口已关闭!\r\n"));
}
stringBox.ID = "2";
stringBox.str = string.Concat(comSerial.getUserPortName(), " <--> 串口已打开!");
OnInfoMsg(stringBox);
}
///
/// 串口发送事件
///
///
public void Com_SendMsgEvent(string param)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
AppendText(param);
}));
}
else
{
AppendText(param);
}
}
///
/// 串口接收事件
///
///
public void Com_RecvMsgEvent(string param)
{
StringBox stringBox = new StringBox();
if (this.InvokeRequired)
{
this.BeginInvoke(new ThreadStart(delegate ()
{
AppendText(param);
}));
}
else
{
AppendText(param);
}
stringBox.str = param;
OnRcvMsg(stringBox);
}
#endregion
}
}