csma/cd协议用 C++语言编程一下
时间: 2023-08-04 07:12:49 浏览: 82
C++模拟CSMACD协议
4星 · 用户满意度95%
CSMA/CD协议是一种用于局域网的传输协议,下面是用C++语言实现的一个简单的CSMA/CD协议示例代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MAX_SIZE = 10;
const int MAX_ATTEMPTS = 16;
// 模拟发送数据
void send(int station) {
cout << "Station " << station << " sending data..." << endl;
srand(time(NULL));
int delay = rand() % 5 + 1; // 随机延迟1-5秒
cout << "Station " << station << " waiting for " << delay << " seconds..." << endl;
for (int i = 0; i < delay; i++) {
cout << ".";
sleep(1);
}
cout << endl;
cout << "Data sent successfully from station " << station << endl;
}
int main() {
int data[MAX_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int attempts = 0;
int station = 0;
bool success = false;
// 模拟发送数据的过程
while (!success && attempts < MAX_ATTEMPTS) {
// 等待一段随机时间
srand(time(NULL));
int wait_time = rand() % 5 + 1; // 随机等待1-5秒
cout << "Waiting for " << wait_time << " seconds..." << endl;
for (int i = 0; i < wait_time; i++) {
cout << ".";
sleep(1);
}
cout << endl;
// 尝试发送数据
if (data[station] != 0) {
send(station);
data[station] = 0;
success = true;
} else {
cout << "Station " << station << " has no data to send." << endl;
}
// 碰撞检测
if (!success) {
cout << "Collision detected!" << endl;
attempts++;
station = rand() % MAX_SIZE; // 随机选择另一个站点
cout << "Station " << station << " will try next." << endl;
}
}
// 输出发送结果
if (success) {
cout << "Data sent successfully!" << endl;
} else {
cout << "Failed to send data after " << attempts << " attempts." << endl;
}
return 0;
}
```
这个示例代码模拟了10个站点(数组`data`),每个站点有一份数据要发送。CSMA/CD协议的过程是每个站点等待一段随机时间后尝试发送数据,如果检测到碰撞,则等待一段时间后重试。如果一个站点成功发送数据,则协议结束。如果所有的站点都无法成功发送数据,则协议失败。这个示例代码使用了随机数和休眠函数来模拟等待和碰撞检测等过程。
阅读全文