31.8 (Transfer last 100 numbers in an ArrayList) Programming Exercise 24.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 ArrayList . Name the server program Exercise31_08Server and the client
program Exercise31_08Client. Assume that the numbers of the long type are
stored in PrimeNumbers.dat in binary format.
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 ArrayList . Name the server program Exercise31_08Server and the client
program Exercise31_08Client. 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; import java.util.ArrayList; public class Exercise08s { 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; ArrayList<Long> list = new ArrayList<>(); input.skipBytes(input.available() - 8 * primeNumbers); for (int i = 0; i < primeNumbers; i++) { list.add(input.readLong()); } input.close(); outputToClient.writeObject(list); } } }
import java.io.*; import java.net.Socket; import java.util.ArrayList; public class Exercise08c { public static void main(String[] args) throws IOException, ClassNotFoundException { Socket socket = new Socket("localhost", 8000); ObjectInputStream fromServer = new ObjectInputStream(socket.getInputStream()); @SuppressWarnings("unchecked") ArrayList<Long> list = (ArrayList<Long>)fromServer.readObject(); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } socket.close(); } }
No comments :
Post a Comment