1、界面效果
2、项目类
2.1 Client 类是用来管理所有的链接对象的相当于一个Model使用,有些字段无用
using System.Net.Sockets;
public class Client
{
/// <summary>
/// 序列号
/// </summary>
public int Number { get; set; }
/// <summary>
/// 用户超密
/// </summary>
public string SuperKey { get; set; }
/// <summary>
/// 用户硬件设备
/// </summary>
public string CID { get; set; }
/// <summary>
/// 用户的套接字
/// </summary>
public Socket socket { get; set; }
/// <summary>
/// 发送信息时间戳
/// </summary>
public DateTime SendTime { get; set; }
/// <summary>
/// 是否过滤
/// </summary>
public bool IsCheck { get; set; }
}
2.2 winfor的页面类 :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class Main : Form
{
public Main()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
/// <summary>
/// 启动监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
SocketServer socketServer = new SocketServer(log, count, prot.Text);
socketServer.StartSocketServer();
}
}
//这个是用来解除跨线程更新的
CheckForIllegalCrossThreadCalls = false;
下面是控件的名称自己设置,启动按钮没改名字默认的:button1
2.3 线程管理类:SocketServer
public class SocketServer
{
/// <summary>
/// 接入池
/// </summary>
private List<Client> clients= new List<Client>();
/// <summary>
/// 监听端口
/// </summary>
private int prot = 8000;
/// <summary>
/// 心跳检测间隔(秒)
/// </summary>
private int HeartTime = 10;
/// <summary>
/// 上次心跳检测时间
/// </summary>
private DateTime CheckHeartTime = DateTime.Now;
/// <summary>
/// 监听对象
/// </summary>
private Socket socketServer = null;
/// <summary>
/// 日志
/// </summary>
private TextBox logBox = new TextBox();
/// <summary>
/// 链接数量
/// </summary>
private Label count = new Label();
/// <summary>
/// 构造方法
/// </summary>
/// <param name="logBox"></param>
public SocketServer(TextBox logBox,Label count,int prot) {
this.logBox = logBox;
this.count = count;
this.prot = prot;
}
/// <summary>
/// 1.先建立socketserver套接字,监听是否有客户端连接。
/// </summary>
public void StartSocketServer()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), prot);
socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketServer.Bind(ipep);
socketServer.Listen(10000);
//启动监听
new Thread(new ParameterizedThreadStart(BeginListen)).Start(); ;
//对所有客户机进行心跳检测
new Thread(new ParameterizedThreadStart(CheckHeart)).Start();
}
/// <summary>
/// 2.待某个客户端连接上时,将客户端client加入到Socket类型的数组client里
/// </summary>
private void BeginListen(object bl)
{
while (true)
{
Socket client = socketServer.Accept();
Client c = new Client();
c.socket = client;
c.IsCheck = false;
c.SendTime = DateTime.Now;
clients.Add(c);
logBox.AppendText(DateTime.Now + " " + ((IPEndPoint)client.RemoteEndPoint).Address + ":接入" + "\r\n");
//渲染链接数量
count.Text = clients.Count.ToString();
//启动会话
new Thread(new ParameterizedThreadStart(ReceiveData)).Start(client);
}
}
/// <summary>
/// 和这个客户端通信(接收这个客户端发送的消息)
/// </summary>
/// <param name="client"></param>
private void ReceiveData(object client)
{
Socket nowClient = (Socket)client;
//不断接收客户端传来的消息,并发送给其他客户端
while (true)
{
int bytes = 0;
byte[] data = new byte[1024];
try
{
bytes = nowClient.Receive(data);//接收客户端传来的消息
}
catch (Exception e)
{
logBox.AppendText(DateTime.Now + " " + ((IPEndPoint)nowClient.RemoteEndPoint).Address + "ERROR:" + e.Message + "\r\n");
}
string message = Encoding.UTF8.GetString(data, 0, bytes);
logBox.AppendText(DateTime.Now+" "+ ((IPEndPoint)nowClient.RemoteEndPoint).Address + ":"+ message + "\r\n");
//将消息发送到其他客户端
}
}
/// <summary>
/// 检测通信的心跳包
/// </summary>
public void CheckHeart(object wt) {
while (true)
{
DateTime now = DateTime.Now;
//超过60s未进行心跳检测
if (CheckHeartTime.AddSeconds(HeartTime) <= now)
{
CheckHeartTime = now;
foreach (var client in clients)
{
//如果未发送消息 或 上次发送时间超过现在时间30s
if (client.SendTime != null && client.SendTime.AddSeconds(30) < now)
{
client.socket.Send(Encoding.UTF8.GetBytes("Hello"));
}
}
count.Text = clients.Count.ToString();
}
else
{
//休息时间差
TimeSpan timeSpan = CheckHeartTime.AddSeconds(HeartTime).Subtract(now);
//休息
Thread.Sleep(Convert.ToInt32(timeSpan.TotalSeconds) * 1000);
}
}
}