1.安装
2. 代码
using STTech.BytesIO.Core;
using STTech.BytesIO.Tcp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace TCP
{
public partial class Form1 : Form
{
private TcpServer server;
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
server = new TcpServer();
server.Port = int.Parse("9000");
server.Started += Server_Started;//开始监听
server.Closed += Server_Closed;//停止监听
server.ClientConnected += Server_ClientConnected;//建立连接
server.ClientDisconnected += Server_ClientDisconnected;//连接断开
server.ClientConnectionAcceptedHandle = (s, e) =>
{
if (server.Clients.Count() < 3)
{
return true;
}
else
{
Print("服务器已满,关闭客户端[" + e.ClientSocket.RemoteEndPoint + "]的连接");
return false;
}
};
}
private void tsmiStart_Click(object sender, System.EventArgs e)
{
server.StartAsync();
}
private void tsmiStop_Click(object sender, System.EventArgs e)
{
server.CloseAsync();
}
//开始监听事件
private void Server_Started(object sender, System.EventArgs e)
{
tbxState.Text = "监听状态:侦听";
tbxState.BackColor = Color.Green;
}
//停止监听事件
private void Server_Closed(object sender, System.EventArgs e)
{
tbxState.Text = "监听状态:断开";
tbxState.BackColor = Color.Red;
}
//建立连接事件
private void Server_ClientConnected(object sender, STTech.BytesIO.Tcp.Entity.ClientConnectedEventArgs e)
{
string str = string.Format("客户端[{0}]:[{1}]连接成功!", e.Client.Host, e.Client.Port);
Print(str);
e.Client.OnDataReceived += Client_OnDataReceived;
e.Client.UseHeartbeatTimeout(5000);//每五秒触发一次心跳确定还在连接
}
//连接中断事件
private void Server_ClientDisconnected(object sender, STTech.BytesIO.Tcp.Entity.ClientDisconnectedEventArgs e)
{
string str = string.Format("客户端[{0}]:[{1}]连接断开!", e.Client.Host, e.Client.Port);
Print(str);
}
//接收到客户端数据
private void Client_OnDataReceived(object sender, STTech.BytesIO.Core.DataReceivedEventArgs e)
{
TcpClient tcpClient = (TcpClient)sender;
Print(e.Data.EncodeToString("GBK"), tcpClient.RemoteEndPoint.ToString());
}
//打印
private void Print(string msg)
{
string str = string.Format("【{0}】:{1}\n", DateTime.Now, msg);
tbxRec.AppendText(str);
}
//打印
private void Print(string msg,string host)
{
string str = string.Format("【{0}】收到客户端{2}信息: {1}\n", DateTime.Now, msg,host);
tbxRec.AppendText(str);
}
}
}
3.界面