The UDP server transmits the list object to the client

Posted by JeremyMorgan on Thu, 09 Dec 2021 14:45:16 +0100

https://www.oschina.net/question/1449495_149180

java serialization:

  1. Java provides a mechanism for object serialization. In this mechanism, an object can be represented as a byte sequence, which includes the data of the object, information about the type of the object and the type of data stored in the object.

  2. After a serialized object is written to a file, it can be read from the file and deserialized, that is, the object type information, the object data, and the data type in the object can be used to create a new object in memory.

  3. The whole process is Java virtual machine (JVM) independent, that is, an object serialized on one platform can be deserialized on a completely different platform.

  4. The classes ObjectInputStream and ObjectOutputStream are high-level data streams that contain methods to deserialize and serialize objects.

Serialization:

public final void writeObject(Object x) throws IOException
The above method serializes an object and sends it to the output stream.

Deserialization:

public final Object readObject() throws IOException, ClassNotFoundException
This method takes the next Object from the stream and deserializes the Object. Its return value is Object, so you need to convert it to the appropriate data type.

How to serialize a class

Note that two conditions must be met for the object of a class to be serialized successfully:

This class must implement Java io. Serializable interface.

public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}

ByteArrayOutputStream class:

Byte array output stream creates a byte array buffer in memory, and all data sent to the output stream is saved in the byte array buffer. There are several ways to create byte array output stream objects.

method:
public byte[] toByteArray()
Create a newly allocated byte array. The size of the array and the size of the current output stream. The content is a copy of the current output stream.

public String toString()
Convert the contents of the buffer into strings, and convert bytes into characters according to the default character encoding of the platform.

udp transfer list object:

server class

public class UDPServer {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		
		DatagramSocket server = null;
		ObjectInputStream ois = null;
		try {
			byte[] buffer = new byte[1024];
			int port = 8888;
			boolean listening = true;
			server = new DatagramSocket(port);
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			
			System.out.println("waiting to receive data...");
			while (listening){
				server.receive(packet); //receive a datagrampacket blockly
				System.out.println("receive from " + packet.getAddress() + ":" + packet.getPort());
				// read
				try {
					ois = new ObjectInputStream(new ByteArrayInputStream(packet.getData()));
					List<Person> ps = (List<Person>)ois.readObject();
					for (Person p : ps){
						System.out.println(p);
					}
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} finally{
					if (ois != null) ois.close();
				}
				//for next packet
				packet.setLength(buffer.length);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (server != null){
				server.close();
			}
		}
	}
}

client class

public class UDPClient {
	public static void main(String[] args) throws UnsupportedEncodingException {
		int bufferSize = 1024;
		
		ObjectOutputStream oos = null;
		DatagramSocket client = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize);
			oos = new ObjectOutputStream(baos);

			List<Person> ps = new ArrayList<>();
			for (int i=0; i<5; i++){
				ps.add(new Person("person1", i+20));
			}
			System.out.println("write data");
			oos.writeObject(ps); //write object to byte output stream
			byte[] data = baos.toByteArray(); // get byte data
			
			int port = 8888;
			client = new DatagramSocket();
			InetAddress address = InetAddress.getByName("localhost");
			//Note the packet size setting
			DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
			System.out.println("start to send data...");
			// send data packet
			client.send(packet);
			System.out.println("finish to send data.");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if (client != null) client.close();
				if (oos != null) oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Topics: Java list udp