In Java, we can have many ways to send and receive data. Some methods are closer to the bottom layer, and some problems need to be solved by programmers themselves, while some methods are relatively high in abstraction and can be used very conveniently. These methods of processing data are from low to high according to the abstraction level:
1. Manual encoding: Use bit operations to encode and parse one by one.
2. Use streams to automatically encode: Use OutputStream and ByteArrayOutputStream in combination.
3. Serialization: Put the data into a data object, serialize the object directly and send it.
It is very convenient to use, but you need to pay attention to the loss of efficiency and the receiver should also use Java.
4.RMI: Send all the calls to the method and directly implement the remote call of the method.
In the lowest level method 1, we need to solve some underlying problems ourselves:
1. Integer sending: Consider whether it is a large tail end or a small tail end, an unsigned or a signed integer.
2. Send strings: Encoding issues should be considered.
3. Types without length limits, such as large integers: to encode a frame frame, distinguish each frame by delimiter or length bits.
Multicast and broadcast
We can unicast a copy of the data to each recipient, but this can be very inefficient.
Only UDP sockets allow broadcasting and multicasting. The difference between the two is that broadcasting will be sent to all reachable hosts on the network, and some operating systems may not allow ordinary users to perform broadcasting operations; while multicasting will only be sent to interested hosts. Specifically, it calls joinGroup() of MulticastSocket to join to the host of the multicast group.
public class MulticastReceiverTest { public static void main(String[] args) throws Exception { final InetAddress address = InetAddress.getByName("224.1.1.1"); final int port = 45599; for (int i = 0; i < 5; i++) { new Thread("Thread #" + i){ @Override public void run() { try { MulticastSocket sock = new MulticastSocket(port); sock.joinGroup(address); byte[] msg = new byte[256]; DatagramPacket packet = new DatagramPacket(msg, msg.length); sock.receive(packet); System.out.println(Thread.currentThread().getName() + " receive: " + new String(packet.getData())); } catch (IOException e) { e.printStackTrace(); } } } }.start(); } Thread.sleep(2000); MulticastSocket sock = new MulticastSocket(); sock.setTimeToLive(32); byte[] msg = "hellomulticast".getBytes(); DatagramPacket packet = new DatagramPacket(msg, msg.length, address, port); sock.send(packet); System.out.println("Message sent"); }}