


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!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
