Java passed the data package delivery object

zhaozj2021-02-08  406

One of Java 1.1 attractive features is new

ObjectInputStream and

ObjectOutputStream These two classes. With this new API (

ObjectOutputStream class

WriteObject (Object O) method and

ObjectInputStream class Object

ReadObject ()), you can get the snapshot of running objects at any time, regardless of it is more complicated. Because this snapshot is passed

ObjectOutputStream class (

The subclasses of the OutputStream class are provided, so you can easily pack it in other output streams, thereby implementing any of the features required (eg

FileoutPutStream).

These new classes provided in Java 1.1 make it possible to transfer operational objects online. To this end, the object and those referenced objects must be serialized - that is, it can be converted into a byte stream. Fortunately, in Java 1.1, most built classes are sequentially. However, some classes are inquirable (Object classes are a typical example). But don't worry. If your class inherits the self-seminated class, you can also serialize the defaultWriteObject () method in the ObjectOutputStream class, which can then be released in the DefaultReadObject () method in the ObjectInputStream class.

Once serialized, the object can be transmitted online. The following example illustrates the method of generating a serialized object and transmitting it through a jacket:

// output objects import java.net *; import java.io *; // class sample to be transmitted:.. Factoryclass Factory implements Serializable {private void writeObject (ObjectOutputStream out) throws IOException {out.defaultWriteObject ();} private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException {in.defaultReadObject ();}} public class ShowObjOutput {public static void main (String [] arg) {try {ObjectOutputStream os; Socket sock = new Socket ( "panda.cs. uno.edu ", 6000); // panda the host name Factory fa = new Factory (); os = new ObjectOutputStream (new BufferedOutputStream (sock.getOutputStream ())); os.writeObject (fa);} catch (IOException ex ) {}}}

The next example illustrates how ObjectInputStream receives objects from the stream jacket:

// object input import java.net *;. Import java.io *;. Public class ShowObjInput {public static void main (String [] arg) {try {ObjectInputStream is; ServerSocket servSock = new ServerSocket (6000); Sock sock; sock = servSock.accept (); Factory o = (Factory) is.readObject ();;} catch (IOException ex) {}}} in addition to tight coupling is = new ObjectInputStream (new BufferedInputStream (sock.getInputStream ())) Outside the socket, Java also provides a DataGramsocket class to support unconnected datagram. Can we use datagram communication to complete object input / output? Complete this feature is not as simple as using the flow sleeve? The problem is that the DataGramsocket is not connected to any stream; in order to perform the sending and reception operation, DataGramsocket uses a byte array as a parameter.

Imagine, in order to construct the data packet, the object must be converted into a byte array. If the object involves a complex object map, this conversion may be extremely difficult. Many of the previously published articles discussed the method of realizing the sequence of objects - the Java object package (serialized) is packed (serialized) the word throttling and the byte flow dispensing is a Java object. However, since the object map may be complicated, the regular object map is converted into byte arrays may need to write a lot of code.

So how do you avoid writing complex packaging code? The following provides a method of transmitting objects using a data packet, and does not need to write packaging code.

The figure above illustrates the data stream when using datagram. As seven steps given below, you can implement this data stream, which can transmit any type of object, MyObject.

first step. Prepare: You can make your object (more than MYOBJECT) by implementing the Serializable interface. The second step. Create a BYTEARRAYOUTPUTSTREAM object, saying that it is called Baostream. third step. Construct an ObjectOutputStream object with Baostream, saying Oostream. the fourth step. Write the object MyObject into Baostream by calling the WriteObject () method of Oostream. the fifth step. Use Baostream's TobyTearRay () method to retrieve the byte array buffers from Baostream. The sixth step. Use the array buffer to construct DataGrampacket by the array buffer retrieved by the fifth step, and say DPACKET. Step 7. Send DPacket by calling the DataGramsocket's Send () method.

To receive the object, complete the steps listed above in an inverse sequence, instead of ObjectOutputStream with ObjectInputStream while replacing ByteArrayoutputStream with ByTearRayinputStream.

When programmed with a socket, SendTo is a standard function that is used in connectionless protocols. In order to be able to transfer objects, I rewrive this function. The following code example shows how to implement the Sender class in the Sender class:

import java.io *;. import java.net *;. public class Sender {public void sendTo (Object o, String hostName, int desPort) {try {InetAddress address = InetAddress.getByName (hostName); ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( 5000); ObjectOutputStream os = new ObjectOutputStream (new BufferedOutputStream (byteStream)); os.flush (); os.writeObject (o); os.flush (); // retrieve the byte array byte [] sendBuf = byteStream.toByteArray ( ); DatagramPacket packet = new DatagramPacket (sendBuf, sendBuf.length, address, desPort); int byteCount = packet.getLength (); dSock.send (packet); os.close ();} catch (UnknownHostException e) {System. Err.Println ("Exception:" E); E.PrintStackTrace ();} catch (ooException e) {E.PrintStackTrace ();}}} The following code list describes how to implement the Receive method in the Receiver class. The RecvobjFROM method is to receive objects for the recipient. You should include this method in your code to receive runtime objects.

import java.io *;. import java.net *;. public class Receiver {public Object recvObjFrom () {try {byte [] recvBuf = new byte [5000]; DatagramPacket packet = new DatagramPacket (recvBuf, recvBuf.length); dSock.receive (packet); int byteCount = packet.getLength (); ByteArrayInputStream byteStream = new ByteArrayInputStream (recvBuf); ObjectInputStream is = new ObjectInputStream (new BufferedInputStream (byteStream)); Object o = is.readObject (); is.close (); Return (O); Catch (ioException e) {system.err.println ("Exception:" E); E.PrintStackTrace ();} catch (classnotfoundexcection e) {E.PrintStackTrace ();} return (null);}} People may worry about the size of the byte array - because when you construct ByTearRayOutputStream or byteArrayInputStream, you must specify the size of the array. Since you don't know the size of the runtime object, you'll be difficult to specify its size. The size of the runtime object is usually unpredictable. Fortunately, Java's BYTEARRAYINPUTSTREAM and BYTEARRAYOUTSTREAM classes can automatically extend their size as needed.

Summary I illustrate a method of using a data packet transmission object by using Java's built-in serialization code. As you can see, the skill is to use byte array streams to fluidize the object into byte arrays.

转载请注明原文地址:https://www.9cbs.com/read-924.html

New Post(0)