连续自动重传协议C sharp实现代码
时间: 2023-05-25 13:03:15 浏览: 112
以下是一个C#实现的Stop-and-Wait ARQ协议(连续自动重传协议)的例子:
using System;
using System.Net;
using System.Net.Sockets;
class Sender {
static void Main(string[] args) {
IPAddress receiverIP = IPAddress.Parse("127.0.0.1");
int receiverPort = 9876;
byte[] data = System.Text.Encoding.ASCII.GetBytes("Hello, world!");
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint receiver = new IPEndPoint(receiverIP, receiverPort);
int seqNumber = 0, ackNumber = 0;
while (data.Length > 0) {
// Send the next packet
byte[] packetData = new byte[512];
packetData[0] = (byte)seqNumber;
packetData[1] = (byte)ackNumber;
packetData[2] = (byte)Math.Min(data.Length, 510); // length of packetData in bytes
Array.Copy(data, 0, packetData, 3, packetData[2]);
sender.SendTo(packetData, packetData.Length, SocketFlags.None, receiver);
// Wait for acknowledgement
bool ackReceived = false;
while (!ackReceived) {
byte[] ackData = new byte[2];
sender.Receive(ackData);
if (ackData[0] == (byte)seqNumber && ackData[1] == (byte)(ackNumber + 1)) {
ackReceived = true;
}
}
// Update seqNumber and ackNumber
seqNumber = 1 - seqNumber;
ackNumber = 1 - ackNumber;
// Remove the data that was just sent
if (data.Length > 510) {
byte[] newData = new byte[data.Length - 510];
Array.Copy(data, 510, newData, 0, data.Length - 510);
data = newData;
} else {
data = new byte[0];
}
}
// Send an empty packet to signal the end of transmission
byte[] endData = new byte[] { (byte)seqNumber, (byte)ackNumber, 0 };
sender.SendTo(endData, endData.Length, SocketFlags.None, receiver);
sender.Close();
}
}
class Receiver {
static void Main(string[] args) {
int receiverPort = 9876;
byte[] buffer = new byte[512];
Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
receiver.Bind(new IPEndPoint(IPAddress.Any, receiverPort));
int seqNumber = 0, ackNumber = 0;
while (true) {
// Wait for a packet
EndPoint sender = new IPEndPoint(IPAddress.Any, 0); // sender IP/port will be filled in by ReceiveFrom
int bytesReceived = receiver.ReceiveFrom(buffer, ref sender);
// Check if it's the end of transmission packet
if (bytesReceived == 3 && buffer[2] == 0) {
break;
}
// Check if the sequence number is correct
if (buffer[0] == (byte)seqNumber) {
// Send an acknowledgement
byte[] ackData = new byte[] { (byte)seqNumber, (byte)(ackNumber + 1) };
receiver.SendTo(ackData, ackData.Length, SocketFlags.None, sender);
// Process the message
byte[] messageData = new byte[buffer[2]];
Array.Copy(buffer, 3, messageData, 0, buffer[2]);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(messageData));
// Update seqNumber and ackNumber
seqNumber = 1 - seqNumber;
ackNumber = 1 - ackNumber;
} else {
// Resend the acknowledgement
byte[] ackData = new byte[] { (byte)(1 - seqNumber), (byte)(1 - ackNumber) };
receiver.SendTo(ackData, ackData.Length, SocketFlags.None, sender);
}
}
receiver.Close();
}
}
阅读全文