当前位置:网站首页>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
边栏推荐
- Color matching and related issues
- 串口调试工具 mobaxterm 下载
- Freescale 单片机概述
- 【leetcode】275. H index II
- Mindspire, a domestic framework, cooperates with Shanshui nature conservation center to find and protect the treasure life in the "China water tower"
- Let agile return to its original source -- Some Thoughts on reading the way of agile neatness
- Introduction to software engineering -- Chapter 4 -- formal description technology
- [微服务]认识微服务
- golang语言的开发学习路线
- The fourth bullet of redis interview eight part essay (end)
猜你喜欢

Can't write to avoid killing and can easily go online CS through defender

不会写免杀也能轻松过defender上线CS

Introduction to message queuing

com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string. at [Source:x

Memorizing byte order of big and small end

How to easily describe the process of machine learning?

巧记大小端字节序

go中的微服务和容器编排

Let agile return to its original source -- Some Thoughts on reading the way of agile neatness

大赛报名 | AI+科学计算重点赛事之一——中国开源科学软件创意大赛,角逐十万奖金!
随机推荐
复杂数据没头绪?
leetcode 1143. Longest common subsequence (medium)
【UVM实战 ===> Episode_3 】~ Assertion、Sequence、Property
Why does EDR need defense in depth to combat ransomware?
炒股手机上开户可靠吗? 网上开户炒股安全吗
用户在hander()goroutine,添加定时器功能,超时则强踢出
Operations research says that in issue 66, Behrman also has "speech phobia"?
Deep learning method for solving mean field game theory problems
Com. Faster XML. Jackson. DataBind. Exc.mismatchedinputexception: tableau ou chaîne attendu. At [Source: X
How to easily describe the process of machine learning?
Using physical information neural network to solve hydrodynamics equations
kubernetes可视化界面dashboard
[微服務]認識微服務
客户端实现client.go客户端类型定义连接
Is it safe to open an account on your mobile phone to buy stocks? Is it safe to open an account online to speculate in stocks
go语言的爬虫和中间件
Simulation of delta variant strain of novel coronavirus (mindsponge application)
在线上买养老年金险正规安全吗?有没有保单?
国内外最好的12款项目管理系统优劣势分析
Lorsque le transformateur rencontre l'équation différentielle partielle