|
| 1 | +// Java code for Checksum_Receiver |
| 2 | +import java.net.*; |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Checksum_Receiver { |
| 7 | + |
| 8 | + // Initialize socket and I/O streams |
| 9 | + private Socket s = null; |
| 10 | + private DataInputStream dis = null; |
| 11 | + private DataOutputStream dos = null; |
| 12 | + |
| 13 | + // Constructor to put ip address and port |
| 14 | + public Checksum_Receiver(InetAddress ip,int port)throws IOException |
| 15 | + { |
| 16 | + |
| 17 | + // Opens a socket for connection |
| 18 | + s = new Socket(ip,port); |
| 19 | + |
| 20 | + dis = new DataInputStream(s.getInputStream()); |
| 21 | + dos = new DataOutputStream(s.getOutputStream()); |
| 22 | + |
| 23 | + while (true) |
| 24 | + { Scanner sc = new Scanner(System.in); |
| 25 | + int i, l, nob, sum = 0, chk_sum; |
| 26 | + |
| 27 | + // Reads the data length sent by sender |
| 28 | + l = dis.readInt(); |
| 29 | + |
| 30 | + // Initializes the arrays based on data length received |
| 31 | + int c_data[] = new int[l]; |
| 32 | + int data[] = new int[l]; |
| 33 | + |
| 34 | + System.out.println("Data received (alond with checksum) is"); |
| 35 | + |
| 36 | + for(i = 0; i< data.length; i++) |
| 37 | + { |
| 38 | + // Reading the data being sent one by one |
| 39 | + data[i] = dis.readInt(); |
| 40 | + System.out.println(data[i]); |
| 41 | + |
| 42 | + // Complementing the data being received |
| 43 | + nob = (int)(Math.floor(Math.log(data[i]) / Math.log(2))) + 1; |
| 44 | + c_data[i] = ((1 << nob) - 1) ^ data[i]; |
| 45 | + |
| 46 | + // Adding the complemented data |
| 47 | + sum += c_data[i]; |
| 48 | + } |
| 49 | + System.out.println("Sum(in ones complement) is : "+sum); |
| 50 | + |
| 51 | + // Complementing the sum |
| 52 | + nob = (int)(Math.floor(Math.log(sum) / Math.log(2))) + 1; |
| 53 | + sum = ((1 << nob) - 1) ^ sum; |
| 54 | + System.out.println("Calculated Checksum is : "+sum); |
| 55 | + |
| 56 | + // Checking whether final result is 0 or something else |
| 57 | + // and sending feedback accordingly |
| 58 | + if(sum == 0) |
| 59 | + { |
| 60 | + dos.writeUTF("success"); |
| 61 | + break; |
| 62 | + } |
| 63 | + else |
| 64 | + { |
| 65 | + dos.writeUTF("failure"); |
| 66 | + break; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + // Closing all connections |
| 71 | + dis.close(); |
| 72 | + dos.close(); |
| 73 | + s.close(); |
| 74 | + } |
| 75 | + |
| 76 | + // Driver Method |
| 77 | + public static void main(String args[])throws IOException |
| 78 | + { |
| 79 | + // Getting ip address on which the receiver is running |
| 80 | + // Here, it is "localhost" |
| 81 | + InetAddress ip = InetAddress.getLocalHost(); |
| 82 | + Checksum_Receiver cr = new Checksum_Receiver(ip,45678); |
| 83 | + } |
| 84 | +} |
0 commit comments