Write Implementation of Cartier Sense Multiple Access Protocol in Python
Write Implementation of Cartier Sense Multiple Access Protocol in Python
Here's an implementation of the Carrier Sense Multiple Access (CSMA) protocol in Python:
Python
import random
class Station:
def __init__(self, name):
self.name = name
self.data = ""
self.backoff_time = 0
def generate_data(self):
self.data = f"Data from Station {self.name}"
def sense_medium(self):
# Simulate sensing the medium for collisions
return random.random() > 0.5
def transmit(self):
# Simulate transmission time
transmission_time = random.randint(1, 5)
print(f"Station {self.name} is transmitting data:
'{self.data}'")
time.sleep(transmission_time)
def listen(self):
# Simulate listening for collisions
time.sleep(random.randint(1, 3))
def backoff(self):
# Simulate exponential backoff
self.backoff_time = random.randint(1, 10) ** 2
print(f"Station {self.name} is backing off for
{self.backoff_time} seconds")
time.sleep(self.backoff_time)
def run(self):
self.generate_data()
while True:
# Check if medium is free
if self.sense_medium():
self.transmit()
break
else:
print(f"Station {self.name} detected a collision")
self.listen()
self.backoff()
if __name__ == "__main__":
# Create stations
stations = [Station(f"Station {i}") for i in range(1, 4)]
This code implements a simple 1-persistent CSMA protocol. Each station has the following
functionalities:
This is a basic implementation and can be further extended to include features like:
● Collision detection
● Different CSMA access modes (non-persistent, p-persistent, o-persistent)
● Error handling and retransmissions
● Network topology and propagation delays
● Visualization of the transmission process
This code can be used as a starting point for further exploration and understanding of the CSMA
protocol. Remember to adapt and modify it based on your specific needs and learning
objectives.