当前位置:网站首页>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
边栏推荐
- Can't write to avoid killing and can easily go online CS through defender
- ASP. Net core create MVC project upload file (buffer mode)
- 炒股手机上开户可靠吗? 网上开户炒股安全吗
- 当Transformer遇见偏微分方程求解
- 想买股票请问在券商公司的哪里开户佣金低更安全
- go语言中的私聊功能处理
- 巧记大小端字节序
- 手机上可以开户炒股吗 网上开户炒股安全吗
- Why does EDR need defense in depth to combat ransomware?
- 软件工程导论——第四章——形式化说明技术
猜你喜欢
![[microservice]eureka](/img/60/e5fa18d004190d4dadebfb16b93550.png)
[microservice]eureka

Memorizing byte order of big and small end

Operations research says that in issue 66, Behrman also has "speech phobia"?

Intrusion trace cleaning

Outside the code: writing is the best way to force growth

一篇文章带你学会容器逃逸
![[microservices] understanding microservices](/img/62/e826e692e7fd6e6e8dab2baa4dd170.png)
[microservices] understanding microservices

Safe and cost-effective payment in Thailand

Kubeadm create kubernetes cluster

go中的微服务和容器编排
随机推荐
Big guys talk about the experience sharing of the operation of the cutting-edge mindspore open source community. Come up with a small notebook!
PHP code audit series (I) basis: methods, ideas and processes
When transformer encounters partial differential equation solution
安利!如何提优质的ISSUE?学霸是这样写的!
The user adds a timer function in the handler () goroutine. If it times out, it will be kicked out
How to open an account on the mobile phone? Is it safe to open an account online and speculate in stocks
技术干货|什么是大模型?超大模型?Foundation Model?
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
The most complete hybrid precision training principle in the whole network
1+1<2 ?! HESIC论文解读
在线上买养老年金险正规安全吗?有没有保单?
为什么EDR需要深度防御来打击勒索软件?
Alibaba cloud server purchase, basic configuration, (xshell) remote connection and environment building
万字详解-MindArmour 小白教程!
Would you like to buy stocks? Where do you open an account in a securities company? The Commission is lower and safer
Super hard core! Can the family photo album on Huawei's smart screen be classified automatically and accurately?
Tensorrt notes (VII) sorting out tensorrt use problems
Let agile return to its original source -- Some Thoughts on reading the way of agile neatness
Memorizing byte order of big and small end
[micro service]nacos