In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the method of conveying objects through Datagram packets in Java". In daily operation, I believe that many people have doubts about the method of conveying objects through Datagram packets in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the method of transmitting objects through Datagram packets in Java?" Next, please follow the editor to study!
One of the attractive features of Java 1.1is the addition of objectInputStream and ObjectOutputStream classes. With this new api (the writeObject (Object o) method in the ObjectOutputStream class and object readObject () in the ObjectInputStream class), you can take a snapshot of the running object at any time, no matter how complex its object graph is. Because this snapshot is provided through the ObjectOutputStream class (a subclass of the OutputStream class), you can easily wrap it in another output stream to implement any required functionality (such as FileOutputStream).
These new classes provided in Java 1.1 make it possible to transfer running objects over the web. To do this, the object and those referenced objects must be serializable-- that is, they can be converted to byte streams. Fortunately, in Java 1.1, most built-in classes are serializable. However, some classes are not serializable (the Object class is a typical example). But don't worry. If your class inherits from a non-serializable class, you can also use the defaultWriteObject () method in the ObjectOutputStream class to serialize, and then you can use the defaultReadObject () method in the ObjectInputStream class to de-serialize.
Once serialized, the object can be transmitted over the Internet. The following example shows how to generate a serializable object and send it through a stream socket:
/ / object output
Import java.NET.*
Import java.io.*
/ / sample class to be sent: Factory
Class 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 hostname
Factory fa = new Factory ()
Os = new ObjectOutputStream (new
BufferedOutputStream (sock.getOutputStream ())
Os.writeObject (fa)
}
Catch (IOException ex)
{}
}
}
The next example shows how ObjectInputStream receives objects from stream sockets:
/ / 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 ()
Is = new ObjectInputStream (new
BufferedInputStream (sock.getInputStream ())
Factory o = (Factory) is.readObject ()
}
Catch (IOException ex)
{}
}
}
In addition to tightly coupled sockets, Java provides DatagramSocket classes to support connectionless Datagram communication. Can we use Datagram communication to complete object input / output? Is this not as easy as using stream sockets? The problem is that DatagramSocket is not connected to any stream; to perform send and receive operations, DatagramSocket takes a byte array as a parameter.
As you can imagine, in order to construct a Datagram packet, the object must be converted into a byte array. If an object involves a complex object graph, this conversion can be extremely difficult to complete. Many previously published articles have discussed ways to serialize objects-packaging (serializing) Java objects into byte streams and unpacking byte streams into Java objects. However, because object graphs can be complex, converting a regular object graph to a byte array may require a lot of code.
So how do you avoid writing complex packaging code? The following provides a way to transfer objects using Datagram packets without writing packaging code.
The figure above illustrates the data flow when using datagrams to transmit objects. You can implement this data stream by following the seven steps given below, which can transfer any type of object, myObject.
The first step. Prepare: make your objects (such as myObject) serializable by implementing the Serializable interface.
Step two. Create a ByteArrayOutputStream object, for example, named baoStream.
Step three. Use baoStream to construct an ObjectOutputStream object, such as ooStream.
Step four. Write the object myObject to baoStream by calling the writeObject () method of ooStream.
Step five. Use the toByteArray () method of baoStream to retrieve the byte array buffer from baoStream.
Step six. Construct a DatagramPacket, such as dPacket, using the array buffers retrieved from step 5.
Step seven. Send the dPacket by calling the send () method of DatagramSocket.
To receive the object, complete the steps listed above in reverse order, using ObjectInputStream instead of ObjectOutputStream and ByteArrayInputStream instead of ByteArrayOutputStream.
SendTo is a standard function used in connectionless protocols when programming with sockets. In order to be able to transfer objects, I rewrote this function. The following code example shows how to implement the send method 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 = .netAddress.getByName (hostName)
ByteArrayOutputStream byteStream = new
ByteArrayOutputStream (5000)
ObjectOutputStream os = new ObjectOutputStream (new
BufferedOutputStream (byteStream))
Os.flush ()
Os.writeObject (o)
Os.flush ()
/ / retrieve 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 (IOException e)
{e.printStackTrace ();}
}
}
The following code listing shows how to implement the receive method in the Receiver class. The recvObjFrom method is for the recipient to receive the object. You should include this method in your code to receive run-time 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 (ClassNotFoundException e)
{e.printStackTrace ();}
Return (null)
}
}
People may be worried about the size of the byte array-- because when you construct a ByteArrayOutputStream or ByteArrayInputStream, you have to specify the size of the array. Since you do not know the size of the runtime object, it is difficult to specify its size. The size of run-time objects is usually unpredictable. Fortunately, Java's ByteArrayInputStream and ByteArrayOutputStream classes automatically expand their size as needed.
At this point, the study on "what is the method of delivering objects through Datagram packets in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.