Explain How To Transport Your Own Custom Objects

Explain How To Transport Your Own Custom Objects


  • 16 Mar, 2012

    In this example, write an array multiplier server. The client sends two objects, each representing an array; the server receives the objects, unpack them by invoking a method and multiplies the arrays together and sends the output array (as an object) to the client. The client unpacks the array by invoking a method and prints the new array.Start by making the class, whose objects will be transportable over sockets, serializable by implementing the Serializable interface as shown in Code SampleCode Sample : SerializedObject.javaimport java.io.*;import java.util.*;public class SerializedObject implements Serializable { private int array[] = null; public SerializedObject() { }public void setArray(int array[]) { this.array = array; } public int[] getArray() { return array; }}The next step is to develop the client. In this example, the client creates two instances of SerializedObject and writes them to the output stream (to the server), as shown from the source code in Code Sample.Code Sample: ArrayClient.javaimport java.io.*;import java.net.*;public class ArrayClient { public static void main(String argv[]) { ObjectOutputStream oos = null; ObjectInputStream ois = null; // two arrays int dataset1[] = {3, 3, 3, 3, 3, 3, 3}; int dataset2[] = {5, 5, 5, 5, 5, 5, 5}; try { // open a socket connectionSocket socket = new Socket("YourMachineNameORipAddress", 4000); // open I/O streams for objectsoos = new ObjectOutputStream(socket.getOutputStream());ois = new ObjectInputStream(socket.getInputStream()); // create two serialized objectsSerializedObject so1 = new SerializedObject();SerializedObject so2 = new SerializedObject(); SerializedObject result = null; int outArray[] = new int[7]; so1.setArray(dataset1); so2.setArray(dataset2); // write the objects to the server oos.writeObject(so1); oos.writeObject(so2); oos.flush(); // read an object from the serverresult = (SerializedObject) ois.readObject(); outArray = result.getArray(); System.out.print("The new array is: ");// after unpacking the array, iterate through it for(int i=0;i<outArray.length;i++) { System.out.print(outArray[i] + " "); } oos.close(); ois.close(); } catch(Exception e) { System.out.println(e.getMessage()); } }}

    Comments Received:
    Please give your suggestions and feedback:

2009-2016 downloadmela.com. All rights reserved.