c#tcp多線程伺服器執行個體代碼

來源:互聯網
上載者:User

標籤:用戶端   threading   mic   network   cat   即時   訊息   .com   執行個體化   

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;
}
}

c#tcp多線程伺服器執行個體代碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.