using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;u ...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using System.Net.NetworkInformation;
namespace 黃炎培_伺服器
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 伺服器傾聽客戶端連接線程
/// </summary>
Thread threadWatchs = null;
/// <summary>
/// 伺服器套接字
/// </summary>
Socket socketServer = null;
/// <summary>
/// 伺服器監控客戶端連接情況的線程
/// </summary>
Thread MonitoThread = null;
/// <summary>
/// 客戶端ip與套接字的集合
/// </summary>
Dictionary<string, Socket> dictSocket = new Dictionary<string, Socket>();
/// <summary>
/// 客戶端ip與線程的集合
/// </summary>
Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
/// <summary>
/// 客戶端連接線程的數量
/// </summary>
long numThreadVal = 0;
/// <summary>
/// 伺服器ip
/// </summary>
string strServerIP = "192.168.4.3";
/// <summary>
/// 伺服器埠
/// </summary>
int serverPort = 8080;
/// <summary>
/// 緩存數據長度
/// </summary>
int receiveDataValLengt = 1024;//緩存區長度
/// <summary>
/// 用於Ping客戶端
/// </summary>
Ping monitoPing = new Ping();
/// <summary>
/// 異常斷開的客戶端
/// </summary>
Dictionary<string, string> dictBodClient = new Dictionary<string, string>();
/// <summary>
/// 指示釋放釋放線程
/// </summary>
bool isClearThread = false;
ulong numDataFlow;
private void Form1_Load(object sender, EventArgs e)
{
//開啟伺服器
openServer(strServerIP, serverPort);
//開啟伺服器監控線程
MonitoThread = new Thread(monitoThreadsDynamic);
//後臺線程
MonitoThread.IsBackground = true;
//啟動線程
MonitoThread.Start();
}
/// <summary>
/// 開始實時監控客戶端的連接情況
/// </summary>
void monitoThreadsDynamic()
{
delegateShowMseeage("開始實時監控客戶端連接情況");
while (true)
{
Thread.Sleep(3000);
try
{
foreach (var vv in dictSocket)
{
PingReply reply = monitoPing.Send(vv.Key.Split(':')[0],1000);
//如果Ping通
if (reply.Status == IPStatus.Success)
{
//表示客戶端連接正常
delegateShowMseeage("客戶端" + vv.Key + "連接正常");
}
else
{
delegateShowMseeage("客戶端" + vv.Key + "連接異常");
//添加異常客戶端連接到集合dictBodClient
dictBodClient.Add(vv.Key, "old");
}
}
//釋放異常連接的線程
foreach (var vvv in dictThread)
{
isClearThread = false;
foreach (var vvvv in dictBodClient)
{
if (vvv.Key == vvvv.Key)
{
isClearThread = true;
break;
}
}
if (isClearThread)
{
vvv.Value.Abort();
delegateShowMseeage("客戶端" + vvv.Key + "占用的線程已釋放");
}
}
//從集合合中移除異常連接的客戶端
foreach (var vvv in dictBodClient)
{
//從集合中移除客戶端套接字
dictSocket.Remove(vvv.Key);
//從集合中移除客戶端線程
dictThread.Remove(vvv.Key);
//從列表中移除客戶端套接字的遠程終結點
deleteClientSocket(vvv.Key);
//跨線程顯示提示數據
delegateShowMseeage("客戶端" + vvv.Key + "斷開連接");
}
}
catch (Exception se)
{
//MessageBox.Show(se.Message);
delegateShowMseeage(se.Message);
}
dictBodClient.Clear();
//獲得當前程式運行的線程總數量
numThreadVal = Process.GetCurrentProcess().Threads.Count;
delegateShowMseeage("當前的線程總數量為:" + numThreadVal);
//獲得客戶端連接所占用的線程數量
numThreadVal = dictThread.LongCount();
//跨線程顯示消息
delegateShowMseeage("其中客戶端連接的線程數量為:" + numThreadVal);
}
}
/// <summary>
/// 開啟伺服器
/// </summary>
/// <param name="serverIP"></param>
/// <param name="serverPort"></param>
void openServer(string serverIP, int serverPort)
{
//實例化伺服器套接字
socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//配置網路端點
IPEndPoint ipAndPort = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
try
{
//設置伺服器套接字的連接參數
socketServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//將網路端點綁定到伺服器套接字
socketServer.Bind(ipAndPort);
}
catch (SocketException se)
{
MessageBox.Show("異常:" + se.Message);
return;
}
//伺服器開始傾聽,指定最多客戶端數量為10000
socketServer.Listen(10000);
//實例化伺服器傾聽客戶端連接的線程
threadWatchs = new Thread(WatchClientConnecting);
//後臺運行線程
threadWatchs.IsBackground = true;
//啟動線程
threadWatchs.Start();
//顯示提示消息
showMesssge("伺服器啟動成功");
}
/// <summary>
/// 開始傾聽客戶端
/// </summary>
void WatchClientConnecting()
{
//跨線程顯示提示消息
delegateShowMseeage("伺服器開始傾聽客戶端連接");
while (true)
{
//傾聽新的客戶端連接請求
Socket newClientConnecting = socketServer.Accept();
//添加客戶端套接字的遠程終結點到列表
addClientSocket(newClientConnecting.RemoteEndPoint.ToString());
//新建一條新的客戶端線程
Thread newClinetThread = new Thread(receiveData);
//後臺運行客戶端
newClinetThread.IsBackground = true;
//啟動線程,並將 新客戶端的套接字 綁定到線程執行的方法
newClinetThread.Start(newClientConnecting);
//添加客戶端套接字到集合
dictSocket.Add(newClientConnecting.RemoteEndPoint.ToString(), newClientConnecting);
//添加客戶端接受數據的線程到集合
dictThread.Add(newClientConnecting.RemoteEndPoint.ToString(), newClinetThread);
//跨線程顯示提示信息
delegateShowMseeage("新客戶端:" + newClientConnecting.RemoteEndPoint.ToString());
}
}
/// <summary>
/// 接受數據
/// </summary>
/// <param name="socketConnecting"></param>
void receiveData(object socketConnecting)
{
//獲取該線程綁定的客戶端套接字
Socket socketClient = socketConnecting as Socket;
while (true)
{
//新建一個緩存區
byte[] receiveDataVal = new byte[receiveDataValLengt];
//數據長度
int receiveDataLength = -1;
try
{
//接受數據填入緩存區並獲得數據長度
receiveDataLength = socketClient.Receive(receiveDataVal);
//接受到數據
if (receiveDataLength > 0)
{
//跨線程顯示接受到的數據
delegateShowReceiveData(socketClient, receiveDataVal, receiveDataLength);
//綜合處理接受到的數據
receiveDataIntegratedProcessing(receiveDataVal, receiveDataLength);
numDataFlow += (uint)receiveDataLength;
showDataFlow();
}
else
{
//從集合中移除客戶端套接字
dictSocket.Remove(socketClient.RemoteEndPoint.ToString());
//從集合中移除客戶端線程
dictThread.Remove(socketClient.RemoteEndPoint.ToString());
//從列表中移除客戶端套接字的遠程終結點
deleteClientSocket(socketClient.RemoteEndPoint.ToString());
//跨線程顯示提示數據
delegateShowMseeage("客戶端" + socketClient.RemoteEndPoint.ToString() + "斷開連接");
//釋放該線程
return;
}
}
catch
{
//從集合中移除客戶端套接字
dictSocket.Remove(socketClient.RemoteEndPoint.ToString());
//從集合中移除客戶端線程
dictThread.Remove(socketClient.RemoteEndPoint.ToString());
//從列表中移除客戶端套接字的遠程終結點
deleteClientSocket(socketClient.RemoteEndPoint.ToString());
//跨線程顯示提示數據
delegateShowMseeage("異常:" + "客戶端" + socketClient.RemoteEndPoint.ToString() + "斷開連接");
//釋放該線程
return;
}
}
}
/// <summary>
/// 綜合處理接受到的數據
/// </summary>
/// <param name="datas"></param>
/// <param name="length"></param>
void receiveDataIntegratedProcessing(byte[] datas, int length)
{
//if (length == 5)
//{
// if (datas[0] == 0x11 && datas[4] == 0x11)
// {
// foreach (var clients in dictSocket)
// {
// newOneThreadSendDataToClient(clients.Value, datas, length);
// }
// }
// else if (datas[0] == 0x12 && datas[4] == 0x12)
// {
// foreach (var clients in dictSocket)
// {
// newOneThreadSendDataToClient(clients.Value, datas, length);
// }
// }
//}
//*******************************************************************
//將接受的數據發送給所有客戶端
//*******************************************************************
//遍歷客戶端套接字的集合
foreach (var clients in dictSocket)
{
//新建一條線程發送數據到客戶端
newOneThreadSendDataToClient(clients.Value, datas, length);
}
}
void newOneThreadSendDataToClient(Socket clientSocket, byte[] datas, int length)
{
//跨線程顯示提示消息
delegateShowMseeage("新建一條線程準備開始發送數據");
//新建發送數據的參數模型
dataSendArgsMode sendDataArgs = new dataSendArgsMode();
//將客戶端套接字綁定到模型
sendDataArgs.sockets = clientSocket;
//將數據綁定到模型
sendDataArgs.datas = datas;
//將數據長度綁定到模型
sendDataArgs.length = length;
//新建發送數據到客戶端的線程
Thread threadSendDataToClient = new Thread(sendDataToClient);
//後臺運行線程
threadSendDataToClient.IsBackground = true;
//啟動線程,並將 發送數據的參數模型 綁定到線程執行的方法
threadSendDataToClient.Start(sendDataArgs);
}
/// <summary>
/// 發送數據到客戶端
/// </summary>
/// <param name="obj"></param>
void sendDataToClient(object obj)
{
//獲取用於發送數據的參數模型
dataSendArgsMode args = obj as dataSendArgsMode;
try
{
//從數據參數模型中提取數據發送到模型中的客戶端
args.sockets.Send(args.datas, 0, args.length, SocketFlags.None);
//跨線程顯示提示消息
delegateShowMseeage("數據:" + getStringFormByte(args.datas, args.length) + "發送到了客戶端:" + args.sockets.RemoteEndPoint.ToString());
delegateShowMseeage("數據發送完畢,關閉線程");
//釋放該線程
numDataFlow += (uint)args.length;
showDataFlow();
return;
}
catch
{
//從集合中移除客戶端套接字
dictSocket.Remove(args.sockets.RemoteEndPoint.ToString());
//從集合中移除客戶端線程
dictThread.Remove(args.sockets.RemoteEndPoint.ToString());
//從列表中移除客戶端套接字的遠程終結點
deleteClientSocket(args.sockets.RemoteEndPoint.ToString());
//跨線程顯示提示消息
delegateShowMseeage("異常:" + "客戶端" + args.sockets.RemoteEndPoint.ToString() + "斷開連接" + ",關閉該線程");
//釋放該線程
return;
}
}
/// <summary>
/// 從列表中刪除客戶端
/// </summary>
/// <param name="socket"></param>
void deleteClientSocket(string strClientSocket)
{
//封裝一個方法進行委托
Action<string> actionDelegate = (x) =>
{
//從列表中移除指定客戶端套接字的遠程終結點
lbOnlineClient.Items.Remove(x.ToString());
};
//將參數委托到指定方法執行
txtMessage.Invoke(actionDelegate, strClientSocket);
}
/// <summary>
/// 添加客戶端到列表
/// </summary>
/// <param name="clientSocket"></param>
void addClientSocket(string strClientSocket)
{
//封裝一個方法進行委托
Action<string> actionDelegate = (x) =>
{
//向列表中添加指定客戶端套接字的遠程終結點
lbOnlineClient.Items.Add(x.ToString());
};
//將參數委托到指定方法執行
txtMessage.Invoke(actionDelegate, strClientSocket);
}
/// <summary>
/// 跨線程顯示接受到的數據
/// </summary>
/// <param name="socket"></param>
/// <param name="datas"></param>
/// <param name="length"></param>
void delegateShowReceiveData(Socket socket, Byte[] datas, int length)
{
//封裝一個方法進行委托
Action<string> actionDelegate = (x) =>
{
//向文本框追加文本
txtMessage.AppendText(System.DateTime.Now.ToString()+ " -> "+ x.ToString() + "\r\n");
txtMessage.ScrollToCaret();
};
//將參數委托到指定方法執行
txtMessage.Invoke(actionDelegate, "收到來自 " + socket.RemoteEndPoint.ToString() + " 的數據:" + getStringFormByte(datas, length));
}
/// <summary>
/// 跨線程顯示數據
/// </summary>
/// <param name="message"></param>
void delegateShowMseeage(string message)
{
//封裝一個方法進行委托
Action<string> actionDelegate = (x) =>
{
if (txtMessage.Text.Length > 2000000)
txtMessage.Text = string.Empty;
//向文本框追加文本
txtMessage.AppendText(System.DateTime.Now.ToString()+" -> " + x.ToString() + "\r\n");
txtMessage.ScrollToCaret();
};
//將參數委托到指定方法執行
txtMessage.Invoke(actionDelegate, message);
}
/// <summary>
/// 顯示數據流量
/// </summary>
void showDataFlow()
{
//封裝一個方法進行委托
Action<string> actionDelegateShowFlow = (x) =>
{
lblDataFlow.Text = x.ToString();
};
//將參數委托到指定方法執行
lblDataFlow.Invoke(actionDelegateShowFlow, numDataFlow.ToString());
}
/// <summary>
/// 顯示數據
/// </summary>
/// <param name="message"></param>
void showMesssge(string message)
{
//向文本框追加文本
txtMessage.AppendText(System.DateTime.Now.ToString() + " -> " + message + "\r\n");
txtMessage.ScrollToCaret();
}
/// <summary>
/// 16進位的字元串形式
/// </summary>
/// <param name="data"></param>
/// <param name="length"></param>
/// <returns></returns>
string getStringFormByte(byte[] data, int length)
{
string str = "";
for (int i = 0; i < length; i++)
{
str += data[i].ToString("X").PadLeft(2, '0') + ' ';
}
return str;
}
}
/// <summary>
/// 發送數據的參數
/// </summary>
class dataSendArgsMode
{
/// <summary>
/// 套接字
/// </summary>
public Socket sockets;
/// <summary>
/// 數據
/// </summary>
public byte[] datas;
/// <summary>
/// 長度
/// </summary>
public int length;
}
}