Related Java Class Introduction
DatagramSocket
public class DatagramSocket extends Object
This class represents a socket used to send and receive datagram packets.
Datagram sockets are the sending or receiving points of packet delivery services. Each packet sent or received on a datagram socket is addressed and routed separately. Multiple packets sent from one machine to another may choose different routes or may arrive in different orders.
UDP broadcast sending is always enabled on DatagramSocket. In order to receive broadcast packets, DatagramSocket should be bound to a wildcard address. In some implementations, broadcast packets can also be received when bound to a more specific address.
Data can be sent and received through the send and receive of DatagramSocket.
public void receive(DatagramPacket p) throws IOException
Receive datagram packets from this socket. When this method returns, the DatagramPacket's buffer is filled with the received data. The datagram packet also contains the sender's IP address and the port number on the sender's machine.
This method blocks until the datagram is received. The length field of the datagram packet object contains the length of the received information. If the information is longer than the length of the packet, the information will be shortened
If a security manager exists and the security manager's checkAccept method does not allow the receive operation, the packet cannot be received.
parameter:
p-The DatagramPacket to place the incoming data.
Throw:
IOException - If an I/O error occurs.
SocketTimeoutException - If setSoTimeout was called previously and the timeout value has expired.
PortUnreachableException - May throw when the socket is connected to the currently unreachable target. Note that there is no guarantee that the exception will be thrown.
IllegalBlockingModeException - If this socket has an associated channel and the channel is in non-blocking mode.
public void send(DatagramPacket p) throws IOException
Send datagram packets from this socket. DatagramPacket contains information indicating: the data to be sent, its length, the IP address of the remote host and the port number of the remote host
If a security manager exists and the socket is not currently connected to the remote address, this method first performs some security checks. First, if p.getAddress().isMulticastAddress() is true, this method calls the security manager's checkMulticast method with p.getAddress() as the parameter. If the value of the expression is false, this method is used to call the security manager's checkConnect method with p.getAddress().getHostAddress() and p.getPort() as parameters. If the operation is not allowed, each call to the Security Manager method will result in a SecurityException.
parameter:
p-DatagramPacket to be sent.
Throw:
IOException - If an I/O error occurs.
SecurityException - If the security manager exists and its checkMulticast or checkConnect methods do not allow sending.
PortUnreachableException - May throw when the socket is connected to the currently unreachable target. Note that there is no guarantee that the exception will be thrown.
IllegalBlockingModeException - If this socket has an associated channel and the channel is in non-blocking mode.
DatagramPacket
public final class DatagramPacket extends Object
This type represents UDP datagram packets, which are used to implement connectionless packet delivery services
Construction method:
DatagramPacket(byte[]buf,intlength)
Construct DatagramPacket to receive data packets of length
DatagramPacket(byte[]buf,intlength,InetAddressaddress,intport)
Construct datagram packets to send packets of length to the specified port number on the specified host
Example of UDP group chat system
UDP is connected without connections. Group chat is to send data to broadcasting address (broadcasting address), so that everyone will receive a message; using the thread method, start a sender thread and the receiver thread, the sender reads the keyboard input as the output, the receiver reads the input information and displays it.
Sender
UdpSender.java
package cn.xidian.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UdpSender extends Thread{@Override public void run() {try {//Create UDP service DatagramSocket socket = new DatagramSocket();//Prepare the data packet to send//Read the input from the system input BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ;String line = null;while((line = in.readLine()) != null){//I did the test and wrote the local address. Group chat needs to write the broadcast address, for example: 192.168.137.255DatagramPacket data = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 9090);//Send data socket.send(data);}//Close socketsocket.close();}catch (IOException e) {e.printStackTrace();}}}Receiver
UdpReceiver.java
package cn.xidian.socket;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;public class UdpReceiver extends Thread {@Override public void run() {try {//Create UDP service and listen to port DatagramSocket socket = new DatagramSocket(9090);//Accept data packets byte[] temp = new byte[1024];DatagramPacket data = new DatagramPacket(temp, temp.length);Boolean flag = true;while(flag){socket.receive(data);//Output the sender's related information String senderAddress = data.getAddress().getHostAddress();String senderHostName = data.getAddress().getHostName();System.out.println(senderHostName+"("+senderAddress+")"+" says: " + new String(temp, 0,data.getLength()));}//Close the resource socket.close();}catch (IOException e) {e.printStackTrace();}}}Main method
UdpMain.java
package cn.xidian.socket;public class UdpMain {public static void main(String[] args) {//Start UdpReceiver thread UdpReceiver receiver = new UdpReceiver();receiver.start();//Start UdpSender thread UdpSender sender = new UdpSender();sender.start();}}Test results
The input party reads the keyboard input as output, the receiver receives the message and displays the sender's IP and host name.
Summarize
The above is all the content of this article about Java programming using UDP to build group chat system code examples. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!