In Java, there are a number of ways we can send and receive data. Some methods are close to the bottom, some problems need to be solved by the programmer, and some methods of abstraction level is relatively high, it is convenient to use. These methods of processing data are based on the abstract hierarchy from low to High, respectively:
1. Manual Coding: Use the bitwise operation to encode and parse one after the other.
2. Use flow to encode automatically: Combine OutputStream and Bytearrayoutputstream.
3. Serialization: Put the data into a data object, serialize the object and send it directly.
It is convenient to use, but pay attention to the loss of efficiency, as well as the receiver to use Java.
4.RMI: The call to the method is passed, and the remote invocation of the method is implemented directly.
At the bottom of Method 1, we need to solve some of the underlying problems ourselves:
1. Integer send: To consider whether the large end or small end, is unsigned or signed integer.
2. Send string: Consider coding problems.
3. No length limit type, such as large integer: to encode frame frames, by delimiter or length bit
to differentiate each frame.
Multicast and broadcast
We can unicast a copy of the data to each recipient, but this may be very inefficient.
Only UDP sockets allow broadcast and multicast, and the difference is that broadcasts are sent to all accessible
Hosts, some operating systems may not allow ordinary users to broadcast; Multicast is only sent to interested
Host. Specifically, a host that calls the MulticastSocket Joingroup () is added to the multicast group.
public class Multicastreceivertest {public static void main (string[] args) throws Exception {final inetaddress add
Ress = 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 {Multicastsock
ET 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");
}
}