Home > Java > javaTutorial > What is the principle of java UDP communication

What is the principle of java UDP communication

王林
Release: 2023-04-28 14:13:06
forward
890 people have browsed it

Principle

1. The UDP protocol is an unreliable network protocol. It establishes a Socket object at both ends of the communication, but these two Sockets are only for sending and receiving. Data object

2. For communication parties based on UDP protocol, there is no so-called client and server concept

Java provides the DatagramSocket class as a Socket based on UDP protocol

Example

package test;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
 
/**
 * UDPCLient deom
 * @author <dht925nerd@126.com>
 */
public class UDPClient {
    public static void main(String[] args) throws Exception {
        DatagramSocket clientSocket = new DatagramSocket();
        BufferedReader inFromUser =
                new BufferedReader(
                        new InputStreamReader(System.in)
                );
        //获取本地 IP 地址
        InetAddress IPAddress = InetAddress.getLocalHost();
        byte[] sendData;
        byte[] receiveData = new byte[1024];
        System.out.println("请输入一句英文,服务器会返回其大写形式(输入exit退出)");
        while (true) {
            String sentence = inFromUser.readLine();
            if (sentence.equals("exit")) break;
            sendData = sentence.getBytes();
            //创建发送数据报包,并标注源地址#,目的地址#
            DatagramPacket sendPacket =
                    new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
            //发送数据报包
            clientSocket.send(sendPacket);
            //创建接收数据报包
            DatagramPacket receivePacket =
                    new DatagramPacket(receiveData, receiveData.length);
            //接收服务器的数据报包
            clientSocket.receive(receivePacket);
            String modifiedSentence = new String(receivePacket.getData());
            System.out.println("FROM SERVER: " + modifiedSentence);
        }
        clientSocket.close();
    }
}
Copy after login

The above is the detailed content of What is the principle of java UDP communication. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template