当前位置:网站首页>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
边栏推荐
- 颜色搭配和相关问题
- Installing MySQL on Ubuntu
- 能在手机上开户炒股吗 网上开户炒股安全吗
- Com. Faster XML. Jackson. DataBind. Exc.mismatchedinputexception: tableau ou chaîne attendu. At [Source: X
- Outside the code: writing is the best way to force growth
- Is it reliable to open an account on a stock trading mobile phone? Is it safe to open an account online and speculate in stocks
- Special topic II on mathematical physics of the sprint strong foundation program
- The user adds a timer function in the handler () goroutine. If it times out, it will be kicked out
- Service discovery, storage engine and static website of go language
- Mindspire, a domestic framework, cooperates with Shanshui nature conservation center to find and protect the treasure life in the "China water tower"
猜你喜欢

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

国产框架MindSpore联合山水自然保护中心,寻找、保护「中华水塔」中的宝藏生命

Special topic II on mathematical physics of the sprint strong foundation program

go语言的服务发现、存储引擎、静态网站

1+1<2 ?! HESIC论文解读

How to easily describe the process of machine learning?

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

用户在hander()goroutine,添加定时器功能,超时则强踢出

Development and learning route of golang language

邮箱附件钓鱼常用技法
随机推荐
论文学习——降雨场次划分方法对降雨控制率的影响分析
Analysis on the advantages and disadvantages of the best 12 project management systems at home and abroad
CVE-2022-30190 Follina Office RCE分析【附自定义word模板POC】
固有色和环境色
Is the low commission free account opening channel safe?
Encapsulate servlet unified processing request
How to open an account on the mobile phone? Is it safe to open an account online and speculate in stocks
手机炒股靠谱吗 网上开户炒股安全吗
Cvpr2022 stereo matching of asymmetric resolution images
Technical dry goods | top speed, top intelligence and minimalist mindspore Lite: help Huawei watch become more intelligent
Technical dry goods | what is a big model? Oversized model? Foundation Model?
客户端实现client.go客户端类型定义连接
技术干货|什么是大模型?超大模型?Foundation Model?
全網最全的混合精度訓練原理
Openpyxl module
入侵痕迹清理
kubernetes可视化界面dashboard
12 color ring three primary colors
PHP code audit series (I) basis: methods, ideas and processes
Special topic II on mathematical physics of the sprint strong foundation program