当前位置:网站首页>Understand the transport layer protocol - tcp/udp
Understand the transport layer protocol - tcp/udp
2022-07-24 02:11:00 【Gold content of Xiaobai】
Catalog
Two important protocols in the transport layer
TCP: Transmission control protocol
class DatagramSocket ( Message socket ) : be used for UDP signal communication
class DatagramPakcet( Packet ): Data abstraction in the communication process
4. Generally used as the method of receiver
1. request (Request)- Respond to (Response) Pattern
2. subscribe (subsrcipt) - radio broadcast (broadcase) Pattern
As a server , We need to create our own Socket object
4.Socket Get communication information
About the use of input and output streams
The difference between data message oriented and byte stream oriented
Two important protocols in the transport layer
First of all, make it clear , Now what to say UDP, And what I'm about to say TCP, These are the types of protocols that work at the transport layer .
UDP: User message protocol
Transport layer protocol , Need to implement the process to Interprocess communication .
Use UDP The two ends of the agreement are not really connected , It's just the dissemination of data .
UDP Nothing has been done , Keep the original ecological state of the network , There is no role to protect the network , So it's not reliable .
TCP: Transmission control protocol
Transport layer protocol , Need to implement the process to Interprocess communication .
Use TCP The protocol will connect the server and the client .
TCP Will do some transmission control , Make communication reliable .
UDP And TCP contrast
The same thing :
It's all transport layer protocols , Need to implement the process to Interprocess communication .
Difference :
UDP: unreliable , There is no connection , A protocol for datagram .
TCP: reliable , There is a connection , A protocol for byte stream .
Five tuple information
Both sides of the communication IP Address + The two sides port( port ) Address + Transport layer protocol = Five tuple information .
Through five tuple information, we can uniquely determine a communication line on the network
Socket (Socket)
Socket The keyword is standing on the application layer , Doing network programming is a very important concept .
Simply speaking , Below the application layer , The computer operating system hardware provides communication ,
And the application layer wants to use network services , Need to use OS Network service window provided Socket To enjoy the service .
Java Used in UDP agreement
class DatagramSocket ( Message socket ) : be used for UDP signal communication
This class is Socket A subclass of class , Copy UDP signal communication , There are two ways to construct it ,
A parameter with port , For servers
A nonparametric structure , For clients

1.UDP The server
We use Socket Constructor creates objects for server-side communication
DatagramSocket socket = new DatagramSocket(PORT);Use a fixed port , To facilitate client communication , There may be a risk of mistakes , For example, when you want to communicate, you find that the port is occupied by other processes .
2.UDP client
Is still Socket Construction method , But there is no need to pass parameters , We only send data to the server as a client , And receive the data replied by the server .
DatagramSocket socket = new DatagramSocket();3. Receive and send
The content sent is the next packet class
// Receiving method
socket.receive(receivedPacket);
// Sending method
socket.send(sentPacket);4. close
After use , Remember to turn off
socket.close();class DatagramPakcet( Packet ): Data abstraction in the communication process
This thing is equivalent to Socket Class to send packets
It contains five tuple information and The data content

1. The receiving party
Just receive a letter , So just take one byte Just receive the package .
// 1. Receiving request
byte[] buf = new byte[1024]; // 1024 Represents the maximum data size we receive ( byte )
DatagramPacket receivedPacket = new DatagramPacket(buf, buf.length);2. The sender
The sender needs to provide the current data content , Already the other party's IP and port
DatagramPacket sentPacket = new DatagramPacket(
bytes, 0, bytes.length, // Data to send
loopbackAddress, TranslateServer.PORT // The other person's ip + port
);3. Generally used as a server
InetAddress address = receivedPacket.getAddress();
Log.println(" The other person's IP Address : " + address);
// Remove the port of the other party
int port = receivedPacket.getPort();
Log.println(" The other person's port: " + port);
// Pull out the other party's ip Address + port
SocketAddress socketAddress = receivedPacket.getSocketAddress();We can get new port , ip As well as data .
obtain port and ip You can send the data back , So this is a common method for servers .
InetAddress address = receivedPacket.getAddress();
Log.println(" The other person's IP Address : " + address);
// Remove the port of the other party
int port = receivedPacket.getPort();
Log.println(" The other person's port: " + port);With these , We can send the data back
First get the information of the other party
// Pull out the other party's ip Address + port
SocketAddress socketAddress = receivedPacket.getSocketAddress();And then use Packet Package and send back
DatagramPacket sentPacket = new DatagramPacket(
sendBuf, 0, sendBuf.length, // Data to send
socketAddress // The address of the object removed from the request envelope (ip + port)
);4. Generally used as the method of receiver
![]()
The receiver needs data , therefore getData Methods are commonly used
byte[] data = receivedPacket.getData();Server and client
Servers are generally said from the perspective of the application layer , Serve the goal
The client is the end that enjoys the service
Common patterns
1. request (Request)- Respond to (Response) Pattern
One request , One response
That means , The client sends the request , The server receives and responds , In this process, the server is passive .
The following figure shows the simple sending of updates , There is no client , Servers , Send data by the sender , The receiving end receives and updates data .

The following figure is more in line with the interaction between the server and the client , The client sends data to the server first , After a series of processing by the server, it will be sent back to the client .

Communication data are all binary data communication , It is shown here as byte[] Spread by .
2. subscribe (subsrcipt) - radio broadcast (broadcase) Pattern
The client subscribes at one time , The server will actively push information to the client regularly .
The server here is relatively active .
UDP summary
1. Network programming
2. How to use ip + port
3.socket Use
4.UDP Characteristics : unreliable , There is no connection , Data oriented message ( The data content is not unpacked during communication , That is, I won't open this letter , There is no problem of data change , The other party can receive the data completely , Of course, the premise is that it spreads )
TCP
TCP It's a reliable , There is a connection , Byte stream oriented protocol
1. Construction method
As a server , We need to create our own Socket object
Use ServerSocket object
ServerSocket serverSocket = new ServerSocket(PORT);As a client, you need to connect to the server
Use Socket object
// Create directly Socket, Use the server IP + PORT
Log.println(" Ready to create socket(TCP Connect )");
Socket socket = new Socket("127.0.0.1", TranslateServerShortConnection.PORT);2.accept
Server's Socket The object is what the receiving client gets , You don't need to create
Listen to the client port , Once there is a client connection , Return a server-side Socket object , And connect with this client until it is closed , In this process, other clients can only block and wait .
Log.println(" Wait for the other party to connect ");
Socket socket = serverSocket.accept();
Log.println(" There is a client connection ");Socket Objects are equivalent to established connections :

3.close
Both client and server can call this method to close communication
socket.close();4.Socket Get communication information
When the server gets Socket Object time , You can call methods to determine each other's information .
// The other person's information :
InetAddress inetAddress = socket.getInetAddress(); // ip
Log.println(" The other person's ip: " + inetAddress);
int port = socket.getPort(); // port
Log.println(" The other person's port: " + port);
SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress(); // ip + port
Log.println(" The other person's ip + port: " + remoteSocketAddress);5. Input stream
When the receiving end receives information , You need to use the input stream to receive
InputStream inputStream = socket.getInputStream();
Scanner scanner = new Scanner(inputStream, "UTF-8");6. Output stream
Send data using output stream
OutputStream os = socket.getOutputStream();
OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8");
PrintWriter writer = new PrintWriter(osWriter);About the use of input and output streams

The difference between data message oriented and byte stream oriented

边栏推荐
- Hospital network security architecture
- jenkins多任務並發構建
- 【MySQL】字符集utf8mb4无法存储表情踩坑记录
- Tdengine helps Siemens' lightweight digital solution simicas simplify data processing process
- jenkins多任务并发构建
- What are the principal guaranteed financial products with an annual interest rate of about 6%?
- WordPress website SEO complete tutorial
- Thread pool interview
- Ardunio - ULN2003 drive board and DC motor fan - control fan speed
- Ora-12899 error caused by nchar character
猜你喜欢
![[重要通知]星球线上培训第三期来袭!讲解如何在QTYX上构建自己的量化策略!...](/img/37/f9ea9af069f62cadff21415f070223.png)
[重要通知]星球线上培训第三期来袭!讲解如何在QTYX上构建自己的量化策略!...

分布式资源管理与任务调度框架Yarn

ACM SIGIR 2022 | interpretation of selected papers of meituan technical team

LoadRunner12安装、录制第一个脚本以及代理服务器没有响应解决

How CAD draws arrows with arcs

Jmeter+influxdb+grafana pressure measurement real-time monitoring platform construction

Local empowerment learning
![STM32 installation tutorial and j-link burning driver installation tutorial [the next day]](/img/09/def640c771f1b9effaaec3844d4cd3.png)
STM32 installation tutorial and j-link burning driver installation tutorial [the next day]

Notes - record the solution to the failure of @refreshscope dynamic refresh configuration

What's new in the ranking list in July? This language is invincible?
随机推荐
Install go environment under Kali
暑假第三周
Qt::WA_ Transparentformouseevents
2022-07-22: what is the output of the following go language code? A:1; B:1.5; C: Compilation error; D:1.49。 package main import “fmt“ func main() { var i
Phpcms realizes product multi condition screening function
利用canvas画图片
Build a CPU Simulator
Number of combinations....
Solve the problem that the script tag is written in front of the element node and cannot get the element node
以科技传递温度,vivo守护生物多样性之美
Halide::Generator生成器使用说明
深入了解-微信开发者工具
Upload files to flash file system through Arduino IDE
Vue3 uses keep alive to cache pages, but every time you switch the tab to enter the page, it will still enter onmounted, resulting in no caching effect. Why?
[bdsec CTF 2022] partial WP
Ardunio - ULN2003 drive board and DC motor fan - control fan speed
canvas-绘图(鼠标按下 绘制 抬起 结束)
[pumpkin Book ml] (task3) decision tree (updating)
What's new in the ranking list in July? This language is invincible?
Wenxin big model raises a new "sail", and the tide of industrial application has arrived