明明客户端已经关闭,但是又立马显示连接成功。
public Form1()
{
InitializeComponent();
menuStrip1.Items[0].Enabled = true;
menuStrip1.Items[1].Enabled = false;
CheckForIllegalCrossThreadCalls = false;
strMesLogPath = AppDomain.CurrentDomain.BaseDirectory + "MesLogs\\"; // 日志记录在运行目录下的MesLogs目录下
server = new TcpServer();
LoadPara();
server.Host = tbIP.Text;
server.Port = int.Parse(tbPort.Text);
server.Started += Server_Started;
server.Closed += Server_Closed;
server.ClientConnected += Server_ClientConnected;
server.ClientDisconnected += Server_ClientDisconnected;
server.ClientConnectionAcceptedHandle = (s, e) => {
if(server.Clients.Count()<10)
{
return true;
}
else
{
AddLog(0, $"服务器已满,关闭[{e.ClientSocket.RemoteEndPoint}]的连接");
return false;
}
};
this.lstLog.Columns[1].Width = this.lstLog.Width - this.lstLog.Columns[0].Width;
}
private void Server_ClientDisconnected(object sender,ClientDisconnectedEventArgs e)
{
AddLog(0, $"客户端[{e.Client.Host}:{e.Client.Port}] 断开连接");
Thread.Sleep(500);
}
private void Server_Closed(object sender, EventArgs e)
{
menuStrip1.Items[0].Enabled = true;
menuStrip1.Items[1].Enabled = false;
AddLog(0,"结束工作");
}
private void Server_ClientConnected(object sender, ClientConnectedEventArgs e)
{
AddLog(1, $"客户端[{ e.Client.Host}:{ e.Client.Port}] 连接成功");
e.Client.OnDataReceived += Client_OnDataReceived;
}
private void Client_OnDataReceived(object sender, STTech.BytesIO.Core.DataReceivedEventArgs e)
{
TcpClient tcpClient = (TcpClient)sender;
AddLog(1, $"来自客户端[{tcpClient.RemoteEndPoint}]的消息: {e.Data.EncodeToString("GBK")}");
string ClientMsg = e.Data.EncodeToString("GBK");
if(!ClientMsg.Contains('\n'))
{
AddLog(0, $"来自客户端[{tcpClient.RemoteEndPoint}]的消息: {e.Data.EncodeToString("GBK")},错误");
return;
}
string[] msg = ClientMsg.Split('\n');
string strJson = JsonData.GetJsonData(msg[1]);
byte[] dateArray = null;
string outStr = "";
try
{
MesFun pMesFunc = new MesFun();
dateArray = pMesFunc.ProcessReceivedString(strJson, outStr);
AddLog(1, $"向客户端[{tcpClient.RemoteEndPoint}]发送消息: {dateArray.EncodeToString("GBK")}");
tcpClient.SendAsync(dateArray);
}
catch (Exception s)
{
AddLog(0, $"调用MES接口失败:[{s.ToString()}]", s);
dateArray = System.Text.Encoding.Default.GetBytes(s.ToString());
tcpClient.SendAsync(dateArray);
}
#if DEBUG
string strMsg = strJson;
dateArray = System.Text.Encoding.Default.GetBytes(strMsg);
AddLog(1, $"向客户端[{tcpClient.RemoteEndPoint}]发送消息: {dateArray.EncodeToString("GBK")}");
tcpClient.SendAsync(dateArray);
#endif
}
private void Server_Started(object sender, EventArgs e)
{
menuStrip1.Items[0].Enabled = false;
menuStrip1.Items[1].Enabled = true;
AddLog(1, "开始工作");
}
private void TsmiStart_Click(object sender, EventArgs e)
{
try
{
server.StartAsync();
}
catch(Exception s)
{
AddLog(0, $"开始失败:[{s.ToString()}]", s);
}
}
private void TsmiClose_Click(object sender, EventArgs e)
{
try
{
server.CloseAsync();
}
catch (Exception s)
{
AddLog(0, $"关闭失败:[{s.ToString()}]", s);
}
}