Sunday, 5 March 2017

Chapter 31 Exercise 7, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

31.7 (Transfer last 100 numbers in an array) Programming Exercise 22.12 retrieves the last 100 prime numbers from a file PrimeNumbers.dat. Write a client program that requests the server to send the last 100 prime numbers in an
array. Name the server program Exercise31_07Server and the client program
Exercise31_07Client. Assume that the numbers of the long type are stored in
PrimeNumbers.dat in binary format.

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Exercise07s {

 public static void main(String[] args) throws IOException {
  @SuppressWarnings("resource")
  ServerSocket serverSocket = new ServerSocket(8000);
  while (true) {
   Socket socket = serverSocket.accept(); 
   ObjectOutputStream outputToClient = new ObjectOutputStream(socket.getOutputStream());
   
   DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream("/tmp/PrimeNumbers.dat")));
   int primeNumbers = 100;
   long[] array = new long[primeNumbers];
   input.skipBytes(input.available() - 8 * primeNumbers);
   for (int i = 0; i < array.length; i++) {
    array[i] = input.readLong();
   }
   input.close();
   
   outputToClient.writeObject(array);
   
  }
 }

}

import java.io.*;
import java.net.Socket;

public class Exercise07c {

 public static void main(String[] args) throws IOException, ClassNotFoundException {
  Socket socket = new Socket("localhost", 8000);
  ObjectInputStream fromServer = new ObjectInputStream(socket.getInputStream());
  long[] array = (long[])fromServer.readObject();
  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
  }
  socket.close();
 }
}

No comments :

Post a Comment