当前位置:网站首页>In depth understanding of UDP in the transport layer and the use of UDP in sockets
In depth understanding of UDP in the transport layer and the use of UDP in sockets
2022-06-27 00:09:00 【Baldness D】
Catalog
One . Study UDP The preparatory knowledge of
1. Familiar with five tuples in network communication
(1) Source IP Address and purpose IP Address
(2) Source port number and destination port number
1.UDP stay socket Classes and methods used in
2. Use DatagramSocket Class to implement a simple word translator ( Including client and server )
3、 ... and .UDP Details of the agreement
3. Based on understanding UDP Some application layer protocols
One . Study UDP The preparatory knowledge of
1. Familiar with five tuples in network communication
(1) Source IP Address and purpose IP Address
Determine the host that sends the message and the host that receives the message .
(2) Source port number and destination port number
Determine which process of the host sent the message and which process in the host that received the message .
Division of port number :0~1023 For well-known port number , Yes HTTP(80 port ),HTTPS(443 port ),FTP(21 port ),SSH(22 port ) Wait for application layer protocol . We should avoid well-known port numbers when writing our own programs , So as to avoid any abnormality .
1024~65535: Port number dynamically assigned by the operating system , The client is allocated by the operating system from this range .
One of the processes can bind multiple port numbers , A port number cannot be bound by multiple processes
(3) Agreement No
The protocol between the sending process and the receiving process .
2. What are client and server

Two .socketAPI in UDP Use
1.UDP stay socket Classes and methods used in
The classes used are DatagramSocket. The common methods are as follows :
| Method name | Method statement |
| DatagramSocket(int port,InetAddress laddr) | Create a datagram socket , Bind to the specified local address |
| DatagramSocket(SocketAddress bindaddr) | Create a datagram socket , Bind to the specified local socket address |
| void bind(SocketAddress addr) | Put this DatagramSocket Bind to a specific address and port |
| void connect(InetAddress address, int port) | Connect the socket to the remote address of this socket |
| void receive(DatagramPacket p) | Receive datagram packets from this socket |
| void close() | Close this datagram socket |
| void send(DatagramPacket p) | Send datagram packets from this socket |
In the use of DatagramSocker The data in is sent in datagrams .
Use this class to send datagrams , The following two constructors are used here .

2. Use DatagramSocket Class to implement a simple word translator ( Including client and server )
(1) Icon

(2) Code implementation
client :
There is also a InetAddress Class

package javaweb.udptcp2.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class UDPClient {
DatagramSocket socket = null;
String serverIp = null;
int serverPort;
// The port number of the client does not need to be bound , Automatically assigned by the system
public UDPClient(String serverIp, int serverPort) throws SocketException {
socket = new DatagramSocket();
this.serverIp = serverIp;
this.serverPort = serverPort;
}
// Start client ( Here you can use a loop to enter requests all the time )
public void start() throws IOException {
System.out.println(" The client starts ");
// Use scanner To enter the request
Scanner sc = new Scanner(System.in);
while (true) {
String request = sc.nextLine();
// Exit client
if("exit".equals(request)) {
break;
}
// Construct datagrams to be sent ( Here, the string data is converted into binary to send )
//InetAddres.getName() Is to determine the host name IP Address
DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
InetAddress.getByName(serverIp), serverPort);
// Send the constructed datagram to the specified client
socket.send(requestPacket);
// Receive requests from the server in the form of datagrams
DatagramPacket responPacket = new DatagramPacket(new byte[4096],4096);
socket.receive(responPacket);
// Convert the received message into a string ( Use trim Is to remove the space before and after the string )
String respons = new String(responPacket.getData(),0,responPacket.getLength()).trim();
// Print the resulting response to the console
System.out.println(respons);
}
}
// Start client
public static void main(String[] args) throws IOException {
// there ip It is the loopback of this machine ip
UDPClient client = new UDPClient("127.0.0.1",9090);
client.start();
}
}
Server side :
package javaweb.udptcp2.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
// Realize a simple English translation server
public class UDPServer {
DatagramSocket socket = null;
// Save words
Map<String, String> words = new HashMap<>();
// Bind the port number to the server
public UDPServer(int port) throws SocketException {
socket = new DatagramSocket(port);
words.put(" cat ","cat");
words.put(" Dog ","dog");
words.put(" fish ","fish");
}
// Start server
public void start() throws IOException {
System.out.println(" The server has started ");
while (true) {
// Receiving requests from clients
DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
socket.receive(requestPacket);
String request = new String(requestPacket.getData(),0,requestPacket.getLength()).trim();
// Construct the response according to the request
String respons = process(request);
// Send the response data to the client
DatagramPacket responsPacket = new DatagramPacket(respons.getBytes(),respons.getBytes().length,requestPacket.getSocketAddress());
socket.send(responsPacket);
// Output the data sent from the server to the client to the console
System.out.printf("[%s:%d]; request:%s respons:%s\n",requestPacket.getAddress().toString()
,requestPacket.getPort(), request, respons);
}
}
// Calculated response
private String process(String request) {
if(words.containsKey(request)) {
return words.get(request);
} else {
return " Not found ";
}
}
// Start server
public static void main(String[] args) throws IOException {
UDPServer server = new UDPServer(9090);
server.start();
}
}
Be careful : Here, the buffer in the datagram is of its own size , If the sent data exceeds the size of the buffer, it will be automatically truncated , So the size here needs to be configured by yourself .
(3) Running results

3、 ... and .UDP Details of the agreement
1.UDP Protocol side format of

Detailed diagram of protocol format :

2.UDP Characteristics
- There is no connection : Know the right side IP And the port number are transmitted directly , No connection needed .
- unreliable : There is no confirmation mechanism , There is no retransmission mechanism ; If the segment cannot be sent to the other party due to network failure , UDP The protocol layer will not return any error information to the application layer .
- For datagram : Can not flexibly control the number and number of reading and writing data . about UDP transmission , If the sender sends 100 Bytes of data , Then the receiving end must also accept 100 Bytes of data , Cannot receive separately .
3. Based on understanding UDP Some application layer protocols
- NFS: Network file system
- TFTP: Simple file transfer protocol
- DHCP: Dynamic Host Configuration Protocol
- BOOTP: Boot protocol ( For diskless device startup )
- DNS: Domain name resolution protocol
边栏推荐
- How to easily describe the process of machine learning?
- 手机上炒股开户可靠吗 网上开户炒股安全吗
- Is the low commission free account opening channel safe?
- [vscode] setting sync, a plug-in for synchronizing extensions and settings
- 技术干货|极速、极智、极简的昇思MindSpore Lite:助力华为Watch更加智能
- Cvpr2022 stereo matching of asymmetric resolution images
- 一篇文章带你学会容器逃逸
- 邮箱附件钓鱼常用技法
- Cve-2022-30190 follina office rce analysis [attached with customized word template POC]
- 冲刺强基计划数学物理专题二
猜你喜欢

Technical dry goods | what is a big model? Oversized model? Foundation Model?

Cvpr2022 stereo matching of asymmetric resolution images

深度学习方法求解平均场博弈论问题

ASP. Net core create MVC project upload file (buffer mode)

Common techniques of email attachment phishing

ASP.Net Core创建MVC项目上传文件(缓冲方式)

我的c语言进阶学习笔记 ----- 关键字

Crawler and Middleware of go language

代码之外:写作是倒逼成长的最佳方式

Introduction to software engineering -- Chapter 4 -- formal description technology
随机推荐
不会写免杀也能轻松过defender上线CS
The client implements client Go client type definition connection
Thesis study -- Analysis of the influence of rainfall field division method on rainfall control rate
How to open an account on the mobile phone? Is it safe to open an account online and speculate in stocks
技术干货|极速、极智、极简的昇思MindSpore Lite:助力华为Watch更加智能
[micro service]nacos
指南针开户安全的吗?
目标追踪拍摄?目标遮挡拍摄?拥有19亿安装量的花瓣app,究竟有什么别出心裁的功能如此吸引用户?
Simple test lightweight expression calculator fly
The most complete hybrid precision training principle in the whole network
Super hard core! Can the family photo album on Huawei's smart screen be classified automatically and accurately?
1+1<2 ?! Interpretation of hesic papers
How do new investors open accounts online? Is it safe to open accounts online and speculate in stocks
Color matching and related issues
炒股手机上开户可靠吗? 网上开户炒股安全吗
The user adds a timer function in the handler () goroutine. If it times out, it will be kicked out
Your connection is not private
go语言的服务发现、存储引擎、静态网站
Deep learning method for solving mean field game theory problems
Crawler and Middleware of go language