-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitStuffingUDPServer.java
More file actions
91 lines (73 loc) · 3.29 KB
/
BitStuffingUDPServer.java
File metadata and controls
91 lines (73 loc) · 3.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.net.*;
class BitStuffingUDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(6789);
System.out.println("UDP Bit Stuffing Server is running on port 6789...");
byte[] receiveBuffer = new byte[1024];
byte[] sendBuffer;
DatagramPacket sendPacket;
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
serverSocket.receive(receivePacket);
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
while (true) {
receiveBuffer = new byte[1024]; // Clear buffer
receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
serverSocket.receive(receivePacket);
String inputData = new String(receivePacket.getData(), 0, receivePacket.getLength());
// Perform Bit Stuffing
String stuffedData = bitStuff(inputData);
System.out.println("Stuffed Data: " + stuffedData);
// Send stuffed data back to client
sendBuffer = ("Stuffed Data: " + stuffedData + "\n").getBytes();
sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
// Perform Bit unstuffing
String originalData = bitUnstuff(stuffedData);
System.out.println("De-Stuffed Data: " + originalData);
}
}
}
// Method to perform bit stuffing
public static String bitStuff(String data) {
StringBuilder stuffedData = new StringBuilder("01111110"); // Start flag byte
int count = 0;
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == '1') {
count++;
stuffedData.append("1");
if (count == 5) {
stuffedData.append("0"); // Stuff a '0' after five consecutive '1's
count = 0;
}
} else {
stuffedData.append("0");
count = 0;
}
}
stuffedData.append("01111110"); // End flag byte
return stuffedData.toString();
}
// Method to perform bit unstuffing
public static String bitUnstuff(String data) {
StringBuilder unstuffedData = new StringBuilder();
int count = 0;
// Remove flag bytes first
String actualData = data.substring(8, data.length() - 8);
for (int i = 0; i < actualData.length(); i++) {
if (actualData.charAt(i) == '1') {
count++;
unstuffedData.append("1");
if (count == 5 && i + 1 < actualData.length() && actualData.charAt(i + 1) == '0') {
i++; // Skip the stuffed '0'
count = 0;
}
} else {
unstuffedData.append("0");
count = 0;
}
}
return unstuffedData.toString();
}
}