Under some circumstances you need to control the speed of sending or receiving data in network.
The speed of network is always measured by kbps, which means how many bits to send within one second.
Well, it’s like a physical exercise in high school. Speed == the amount of data / time interval
So there are two points we need to control: the amount of data and the time interval. And by controlling the two points we can control the speed.
There are two ways to implement speed control:
1, first we decide the time interval, after that we can count the max amount of bits to send within the period. And in each time period we send less data than the max amount.
It’s better to set time interval longer than one blocking sending time. The sending bytes works like a ruler, control the accuracy of speed control.
There is the sample code:
// global event to notify the arrival of time internal // initialized with non signal state QEvent g_event; #define TIME_INTERNAL 200 void OnTimer(UINT nIDEvent) { g_event.notify(); return; } void startSendData() { // first count the bytes to send per interval int iRat = GetDlgItemInt(IDC_EDIT_RATE);//kbps int iBytePerCP = iRat * 1000 / 8 * TIME_INTERNAL / 1000; // begin timer SetTimer(NULL, TIME_INTERNAL, NULL); // start sending thread m_hTheadR = CreateThread(NULL, 0, readEmmThread, (LPVOID)&m_ThInof, NULL, NULL); } // sending thread DWORD WINAPI sendEmmThread(LPVOID lpParameter) { int iCountSended = 0; while (TRUE) { // send data... iCountSended += send(...); // for speed control if (iCountSended >= iCountOnce) { g_event.wait(); iCountSended = 0; } } }
2, if every send block have the same size, it’s no need to use a thread to send data, just send data in the OnTimer function. First decide how many bytes to send, then calculate time interval. Set timer and in OnTimer function send those bytes. But you must be sure within the interval all bytes can be send.
Each implement needs a timer, which to indicate begin of new interval. There are various types of timer which we may discuss later.
Of course you may use advanced technical such as QOS.

本文介绍在网络通信中控制数据发送速度的两种方法:一是通过设定时间间隔来限制每段时间内发送的最大数据量;二是若每次发送的数据块大小固定,则直接在定时器回调函数中发送数据即可。两种方式都需要用到定时器来标记新的时间间隔的开始。
810

被折叠的 条评论
为什么被折叠?



