Broadcast form based on UDP in Java (example explanation)

UDP --- user datagram protocol is a simple datagram oriented transport layer protocol. UDP does not provide reliability. It just sends the datagrams sent by the application to the IP layer, but it does not guarantee that they can reach the destination or the order of packets. Because UDP does not need to establish a connection between the client and the server before transmitting datagrams, and there is no timeout retransmission mechanism, the transmission speed is very fast.

Implementation of UDP in Java:

* UDP:

*Client:

* 1. Create socket object for UDP communication -- datagram socket (for sending and receiving UDP data) -- datagram socket

* 2. Prepare data and package - datagram packet

* 3. Send data through the send method

* 4. Close socket object -- socket object

*Server side: receiving data

* 1. Create a socket object and bind the port number

* 2. Create a package object, create an empty array, and prepare to receive data

* 3. receive data

* 4. close resource

*UDP broadcast mode:

*All hosts in the same network segment can receive on the premise that the port should listen

*The client sends the broadcast, and the server that opens the port to listen receives and prints the message

*Broadcast implementation: the client sends the broadcast and the server receives it

* String host = "255.255.255.255";// Broadcast address -- represents all hosts

* 10.0. 122.255 ---- represents that the first three network segments are 10.0 122 all hosts

Code implementation:

Client (sender):

Server side (receiving side):

result:

The first three segments are 10.0 The server with port number 4000 on all hosts of 122 can receive as long as it is turned on---

Client: ha ha....

The above broadcast form (example explanation) based on UDP in Java is all the content shared by Xiaobian. I hope it can give you a reference and support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>