


Detailed explanation of the sender and receiver examples of simulating UDP transmission in Java
This article mainly introduces relevant information about the detailed explanation of the sender and receiver instances of simulated UDP transmission in java. Friends in need can refer to
The sender and receiver of simulated UDP transmission in java Detailed explanation of the receiving end example
1. Create the sending end of UDP transmission
1. Establish the UDP Socket service;
2. Encapsulate the data to be sent into a data packet;
3. Send the data packet through the UDP Socket service;
4. Close the Socket service.
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPSend { public static void main(String[] args) throws IOException { System.out.println("发送端启动......"); // 1、创建UDP的Socket,使用DatagramSocket对象 DatagramSocket ds = new DatagramSocket(); // 2、将要发送的数据封装到数据包中 String str = "UDP传输演示:I'm coming!"; byte[] buf = str.getBytes(); //使用DatagramPacket将数据封装到该对象的包中 DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.1"), 10000); // 3、通过UDP的Socket服务将数据包发送出去,使用send方法 ds.send(dp); // 4、关闭Socket服务 ds.close(); } }
2. Create a receiving end for UDP transmission
1. Establish a UDP Socket service. Because you want to receive data, you must specify a port number;
2. Create a data packet to store the received data and facilitate parsing the data using the data packet object method;
3. Use the receive method of the UDP Socket service Receive data and store it in the data packet;
4. Parse the data through the data packet method;
5. Close the Socket service.
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPReceive { public static void main(String[] args) throws IOException { System.out.println("接收端启动......"); // 1、建立UDP的Socket服务 DatagramSocket ds = new DatagramSocket(10000); // 2、创建数据包 byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); // 3、使用接收方法将数据存储到数据包中 ds.receive(dp); // 该方法为阻塞式的方法 // 4、通过数据包对象的方法解析这些数据,例如:地址、端口、数据内容等 String ip = dp.getAddress().getHostAddress(); int port = dp.getPort(); String text = new String(dp.getData(), 0, dp.getLength()); System.out.println(ip + ":" + port + ":" + text); // 5、关闭Socket服务 ds.close(); } }
3. Optimize the sending and receiving ends of UDP transmission
Since in the first two parts, we can only send (or receive) one message at a time, and then Just shut down the service! Therefore, if we want to send multiple messages, we need to constantly modify the content sent on the sending end, and we also need to restart the server, which is quite troublesome. In order to overcome the above shortcomings, we can optimize it, namely:
1. On the sending end, create a BufferedReader and enter the content from the keyboard;
2. On the receiving end, add a while(ture) loop to continuously receive content in a loop.
/** *优化UDP传输的发送端 */ 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 UDPSend { public static void main(String[] args) throws IOException { System.out.println("发送端启动......"); // 创建UDP的Socket,使用DatagramSocket对象 DatagramSocket ds = new DatagramSocket(); BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); String line = null; while ((line = bufr.readLine()) != null) { // 使用DatagramPacket将数据封装到该对象的包中 byte[] buf = line.getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.1"), 10000); // 通过UDP的Socket服务将数据包发送出去,使用send方法 ds.send(dp); // 如果输入信息为over,则结束循环 if ("over".equals(line)) break; } // 关闭Socket服务 ds.close(); } }
/** *优化UDP传输的接收端 */ import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPReceive { public static void main(String[] args) throws IOException { System.out.println("接收端启动......"); // 建立UDP的Socket服务 DatagramSocket ds = new DatagramSocket(10000); while(true) { // 创建数据包 byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); // 使用接收方法将数据存储到数据包中 ds.receive(dp); // 该方法为阻塞式的方法 // 通过数据包对象的方法解析这些数据,例如:地址、端口、数据内容等 String ip = dp.getAddress().getHostAddress(); int port = dp.getPort(); String text = new String(dp.getData(), 0, dp.getLength()); System.out.println(ip + ":" + port + ":" + text); } } }
4. Create a chat room
According to the relevant properties of UDP (User Datagram Protocol, User Datagram Protocol), we can further create a simple UDP-based transmission The chat room under the agreement realizes the function of interactive chat.
/** *创建UDP传输下的聊天室发送端 */ package chat; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Send implements Runnable { private DatagramSocket ds; public Send(DatagramSocket ds) { this.ds = ds; } public void run() { try { BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); String line = null; while ((line = bufr.readLine()) != null) { byte[] buf = line.getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.255"), 10001); ds.send(dp); if ("886".equals(line)) break; } ds.close(); } catch (Exception e) { System.out.println("对不起,发生错误啦!"); } } }
/** *创建UDP传输下的聊天室接收端 */ package chat; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Rece implements Runnable { private DatagramSocket ds; public Rece(DatagramSocket ds) { this.ds = ds; } public void run() { try { while (true) { byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); String ip = dp.getAddress().getHostAddress(); String text = new String(dp.getData(), 0, dp.getLength()); System.out.println(ip + ":::" + text); if(text.equals("886")){ System.out.println(ip+"......退出聊天室!"); } } } catch (Exception e) { System.out.println("对不起,发生错误啦!"); } } }
/** *创建UDP传输下的聊天室 */ package chat; import java.io.IOException; import java.net.DatagramSocket; public class ChatRoom { public static void main(String[] args) throws IOException { DatagramSocket send = new DatagramSocket(); DatagramSocket rece = new DatagramSocket(10001); new Thread(new Send(send)).start(); new Thread(new Rece(rece)).start(); } }
The above is the detailed content of Detailed explanation of the sender and receiver examples of simulating UDP transmission in Java. For more information, please follow other related articles on the PHP Chinese website!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
