|
| 1 | +// Java program to illustrate Client side |
| 2 | +// Implementation using DatagramSocket |
| 3 | +import java.io.IOException; |
| 4 | +import java.net.DatagramPacket; |
| 5 | +import java.net.DatagramSocket; |
| 6 | +import java.net.InetAddress; |
| 7 | +import java.util.Scanner; |
| 8 | + |
| 9 | +public class udpBaseClient_2 |
| 10 | +{ |
| 11 | + public static void main(String args[]) throws IOException |
| 12 | + { |
| 13 | + // Setting maximum data length |
| 14 | + int MAX = 100; |
| 15 | + Scanner sc = new Scanner(System.in); |
| 16 | + |
| 17 | + // Step 1:Create the socket object for |
| 18 | + // carrying the data. |
| 19 | + DatagramSocket ds = new DatagramSocket(); |
| 20 | + |
| 21 | + InetAddress ip = InetAddress.getLocalHost(); |
| 22 | + byte buf[] = null; |
| 23 | + |
| 24 | + int i, l, sum = 0, nob; |
| 25 | + System.out.print("Enter data length : "); |
| 26 | + l = sc.nextInt(); |
| 27 | + |
| 28 | + // Array to hold the data being entered |
| 29 | + int data[] = new int[MAX]; |
| 30 | + |
| 31 | + // Array to hold the complement of each data |
| 32 | + int c_data[] = new int[MAX]; |
| 33 | + |
| 34 | + System.out.println("Enter data to send : "); |
| 35 | + |
| 36 | + for (i = 0; i < l; i++) |
| 37 | + { |
| 38 | + data[i] = sc.nextInt(); |
| 39 | + |
| 40 | + // Complementing the entered data |
| 41 | + // Here we find the number of bits required to represent |
| 42 | + // the data, like say 8 requires 1000, i.e 4 bits |
| 43 | + nob = (int)(Math.floor(Math.log(data[i]) / Math.log(2))) + 1; |
| 44 | + |
| 45 | + // Here we do a XOR of the data with the number 2^n -1, |
| 46 | + // where n is the nob calculated in previous step |
| 47 | + c_data[i] = ((1 << nob) - 1) ^ data[i]; |
| 48 | + |
| 49 | + // Adding the complemented data and storing in sum |
| 50 | + sum += c_data[i]; |
| 51 | + } |
| 52 | + // The sum(i.e checksum) is also sent along with the data |
| 53 | + data[i] = sum; |
| 54 | + l += 1; |
| 55 | + |
| 56 | + System.out.println("Checksum Calculated is : " + sum); |
| 57 | + System.out.println("Data being sent along with Checksum..."); |
| 58 | + |
| 59 | + // Sends the data length to receiver |
| 60 | + // convert the input into the byte array. |
| 61 | + String temp = Integer.toString(l); |
| 62 | + buf = temp.getBytes(); |
| 63 | + |
| 64 | + // Step 2 : Create the datagramPacket for sending |
| 65 | + // the data. |
| 66 | + DatagramPacket DpSend = new DatagramPacket(buf, buf.length, ip, 1234); |
| 67 | + |
| 68 | + // Step 3 : invoke the send call to actually send |
| 69 | + // the data. |
| 70 | + ds.send(DpSend); |
| 71 | + |
| 72 | + // Sends the data one by one to receiver |
| 73 | + for (int j = 0; j < l; j++){ |
| 74 | + temp = Integer.toString(data[j]); |
| 75 | + buf = temp.getBytes(); |
| 76 | + DpSend = new DatagramPacket(buf, buf.length, ip, 1234); |
| 77 | + ds.send(DpSend); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments