前言:
项目中,服务端和客户端之间大多都是保持长连接的方式,但是后面遇到了一个与生产线上的Mes系统通讯的项目,由于现场的网络经常会出现连接异常的情况,于是就想到了这种短连接的方式(服务端长期处于监听状态,客户端则只在需要收发数据的时候连接上来,收发数据之后再次断开)。后来无意间就找到Simple TCP 这个好用的外部库,开发也是非常的 simple and friendly!非常适合偷懒。。。
1. 窗体布局:
2. 服务端代码:
//初始化服务器
public SimpleTcpServer server = new SimpleTcpServer();
/// <summary>
/// 监听端口
/// </summary>
public void StartListen()
{
//设置编码格式,默认是UTF8
server.StringEncoder = System.Text.ASCIIEncoding.ASCII;
server.Delimiter = Encoding.ASCII.GetBytes("\r")[0];
//数据接收数据
server.DataReceived += (sender, msg) =>
{
// 接收字节数组
// byte[] bytData = msg.Data;
WriteMsg(msg.MessageString);
};
//客户端连接事件
server.ClientConnected += (sender, msg) =>
{
WriteMsg("ClientConnected:" + msg.Client.RemoteEndPoint.ToString());
};
//客户端断开事件
server.ClientDisconnected += (sender, msg) =>
{
WriteMsg("ClientDisconnected:" + msg.Client.RemoteEndPoint.ToString());
};
//开始监听
server.Start(IPAddress.Parse(txt_ServerIPAddress.Text.Trim()), Convert.ToInt32(nud_ServerPort.Value));
Task.Factory.StartNew(() =>
{
while (true)
{
//连接数监控
//int clientsConnected = server.ConnectedClientsCount;
Task.Delay(1000).Wait();
}
}, TaskCreationOptions.LongRunning);
}
// 服务端发送数据
private void btn_ServerSend_Click(object sender, EventArgs e)
{
server.Broadcast("Server to client: " + txt_ServerMsg.Text.Trim()); //发送数据
}
3.客户端代码
//初始化客户端
public SimpleTcpClient client = new SimpleTcpClient();
/// <summary>
/// 连接到服务端
/// </summary>
public void StartConnect()
{
//设置编码格式,默认是UTF8
client.StringEncoder = System.Text.ASCIIEncoding.ASCII;
//设置分隔符,默认是0x13
client.Delimiter = Encoding.ASCII.GetBytes("\r")[0];
//收到数据的事件,可以在这里实现自己的协议
client.DataReceived += (sender, msg) =>
{
//将收到的字节数组转为string
//string bytData = BitConverter.ToString(msg.Data);
//字符串消息
WriteMsg(msg.MessageString);
};
bool exit = false;
bool connected = false;
Task.Factory.StartNew(() =>
{
while (!exit)
{
try
{
if (connected)
{
//发送心跳
client.Write("-");
Task.Delay(10000).Wait();
}
else
{
//断线重连
client.Connect(txt_ClientIPAddress.Text.Trim(), Convert.ToInt32(nud_ClientPort.Value));
connected = true;
Task.Delay(1000).Wait();
}
}
catch (Exception)
{
connected = false;
client.Disconnect();
}
}
}, TaskCreationOptions.LongRunning);
}
private void btn_ClientSend_Click(object sender, EventArgs e)
{
client.Write("Client to server: " + txt_ClientMsg.Text.Trim());
}
4. 运行测试:
5. DLL文件: