当前位置:网站首页>TCP and UDP, TCP server and client, UDP server and client
TCP and UDP, TCP server and client, UDP server and client
2022-07-19 01:41:00 【Don't null Yes】
Catalog
TCP Three handshakes and four waves
UDP And TCP The difference between
TCP
Transmission control protocol (TCP,Transmission Control Protocol) It's a connection oriented 、 reliable 、 Transport layer communication protocol based on byte stream , from IETF Of RFC 793 Definition .TCP It is designed to adapt to the hierarchical protocol hierarchy supporting multi network applications .
The main features
TCP Is a wide area network oriented communication protocol , The goal is to communicate across multiple networks , Provide a communication mode between two communication endpoints with the following characteristics :
- Reliable means of communication ;
- Flow based approach ;
- Connection oriented ;
- When the network condition is not good, try to reduce the bandwidth cost caused by retransmission ;
- Communication connection maintenance is oriented to the two endpoints of communication , Without considering the intermediate network segment and node .
TCP Three handshakes and four waves
TCP It's the transport layer protocol in the Internet , Use three handshake protocol to establish connection . Three handshakes are required to establish a connection , And it takes four handshakes to terminate a connection , This is from TCP Half closed (half-close) Caused by the .
Three handshakes :
- client A Send a connection request to the server B;
- The server B Received client A The message sent must be confirmed , So give it to the server B Send status code , And enter SYN_RECV state ;
- client A Received server B Respond to the server after the status of B, And enter Established state .
Three handshakes complete ,TCP The client and server successfully established the connection , It's time to start transmitting data .
Four waves :
- If the client A Think data transmission is complete , Then it needs to go to the server B Send connection release request .
- B After receiving the connection release request , Tell the application layer to release TCP Connect , Then it will send ACK package , And enter CLOSE_WAIT state , At this point, it means A To B The connection of has been released , No longer receive A Data sent . But because TCP The connection is two-way , therefore B You can still send data to A.
- B If there is still unfinished data at this time, it will continue to send , When it's done, I'll go to A Send connection release request , then B Then enter LAST-ACK state .
- A After receiving the release request , towards B Send a confirmation response , here A Get into TIME-WAIT state . When B After receiving the confirmation reply , And then I went into CLOSED state .
Why three handshakes when connecting , It takes four waves to close the connection ?
Because when Server End receipt Client Terminal SYN After connecting the request message , It can be sent directly SYN+ACK message . among ACK Messages are used to answer ,SYN Messages are used to synchronize . But when you close the connection , When Server End receipt FIN When the message , It's not likely to shut down immediately SOCKET, So you can only reply one first ACK message , tell Client End ," You sent it FIN I received the message ". Only when Server All messages are sent , I can send FIN message , So we can't send .
net modular
net The core module is used to create TCP Connections and services , Encapsulates most of the underlying classes and methods .
When using , You need to import this module : const net = require('net')
net Method
net.createServer([options][, connectionListener])
Create a TCP The server . Parameters connectionListener Automatic feed 'connection' Event creation listener .
net.connect(path[, connectListener])
Create a connection to path Of unix socket . Parameters connectListener Will be added as a listener to 'connect' Incident . return 'net.Socket'.
net.Socket object yes TCP The abstraction of .net.Socket The example implements a duplex stream interface . They can create clients in the user ( Use connect()) When using , Or by Node Create them , And pass connection Server events are passed to users .
UDP
Internet The protocol set supports a connectionless transport protocol , This protocol is called user datagram protocol (UDP,User Datagram Protocol).UDP Provides an application with a way to send encapsulation without establishing a connection IP The packet approach .
The main features
- Facing connectionless . No connection agreement , No connection between source and terminal is established before data transmission , When it wants to transfer, it simply grabs the data from the application , And throw it on the Internet as soon as possible .
- Support one to many , Many to many , Many to one transmission mode .
- UDP The title of the packet is very short , Only 8 Bytes .
- UDP It's message oriented .
- although UDP It's an unreliable agreement , But it's an ideal protocol for distributing information .
UDP And TCP The difference between
UDP and TCP The main difference between the two protocols is how to achieve reliable transmission of information .
| TCP | UDP | |
|---|---|---|
| Is it connected | Connection oriented | There is no connection |
| reliable | Reliable transmission , Use flow control | Unreliable transmission , Do not use flow control |
| Number of connected objects | It can only be one-to-one communication | Support one-to-one , One to many , Many to one and many to many |
| transport | Byte stream oriented | Message oriented |
| First cost | The first byte is the smallest 20 Maximum 60 | Small overhead of the first part , only 8 byte |
| Applicable scenario | Applications requiring reliable transmission ( File transfer ) | Real time applications (IP Telephone , Video conference, etc ) |
TCP Provide reliable connection oriented services to the upper layer ,UDP Provide connectionless and unreliable services to the upper layer .
although UDP did not TCP Accurate transmission , But it is suitable for places with high real-time .
High requirements for data accuracy , The speed can be selected relatively slowly TCP.
dgram modular
stay Node.js in , Provides dgram modular , Used to create UPD Server and client , And realize UDP Communication between server and client .
When using , You need to import this module : const dgram = require('dgram')
TCP Server and client of
Be careful : When it starts , We should be Start the server first and then the client .( It's equivalent to users calling customer service , Only when customer service exists , The user's phone can be dialed , Customer service is equivalent to server , Users are equivalent to clients )
establish TCP The server
// Import net modular
const net = require('net')
// establish TCP The server
const server = net.createServer((client)=>{ //'client' Represents the client
var clientNo = 0 // Number each client connected to the server
console.log(clientNo+' Client number already connected ');
// binding “end” event , Triggered when client disconnects
client.on('end',function(){
console.log(clientNo+' Client number has been disconnected ');
})
client.write(clientNo+' Client number , Hello !');
client.pipe(client);
// binding ‘data’ event , Triggered when data is received
client.on('data',(data=>{
console.log(clientNo+' The data sent by client number is :'+data.toString());
}))
})
// binding ‘error’ event , Print an error message when a connection error occurs
server.on('errot',(err=>{
throw err;
}))
// Start listening , Specify the listening interface
server.listen(8234,()=>{
console.log('TCP The server has started ')
})establish TCP client
const net = require('net')
// establish TCP client
var client = net.Socket();
// Connect to server : call connect Method
client.connect(8234,'127.0.0.1',()=>{
console.log(' Already connected to the server ');
client.write(' I am a TCP The server '); // Send data to the server
})
// Receive server-side data : binding ‘data’ event
client.on('data',(data)=>{
console.log(' Received server-side data :'+data.toString());
})
// monitor ‘end’ event
client.on('end',()=>{
console.log(' End data !');
})Sample results :

UDP Server and client of
establish UDP The server
// Import dgram modular
const dgram = require('dgram');
// establish dgram.Socket object ( Server side --- The receiving end of the data )
const server = dgram.createSocket('udp4');
// binding “error” event
server.on('error',(err=>{
console.log(` Server exception :${err.stack}`);
}))
// binding ‘message’ event , Parameters msg Data sent by the client , Parameters rinfo Encapsulates the information of the client ( Include address 、 Port number, etc )
server.on('message',((msg,rinfo)=>{
var str_msg = msg.toString();
console.log(` The server receives data from :${rinfo.address}:${rinfo.port} Of ${str_msg}`);
console.log(rinfo);
server.send(' Xi'an University of Posts and Telecommunications ',rinfo.port,rinfo.address); // Send data to client
}))
// Register to listen
server.on('listening',()=>{
var server_address = server.address(); // Get the address of the server
console.log(` Server listening :${server_address.address}:${server_address.port}`);
})
// Binding port : Listen for information from this port
server.bind(41234);establish UDP client
const dgram = require('dgram');
const client_msg = Buffer.from(' Hello , I am a UDP The client of ');
// Create client's Socket
const client = dgram.createSocket('udp4');
// The binding event
client.on('close',()=>{
console.log('Scoket closed ')
})
client.on('error',(err=>{
console.log(err);
}))
client.on('message',((msg,rinfo)=>{
if(msg == 'exit'){
client.close();
}
console.log(` Received from server ${rinfo.address}:${rinfo.port} Information about :${msg.toString()}`);
}))
// Send data to the server 41234 Is the server port , Callback function
client.send(client_msg,41234,'localhost',(error=>{
if(error){
client.close();
}
}))Sample results :

边栏推荐
猜你喜欢

Use leaflet to copy the original shentiwa Mega map to make a diary

Uni app wechat official account (4) - address management page

How does the website count the number of visitors? How to install and use 51la?

NFT数字藏品平台有哪些?哪些平台值得珍藏?

一文揭秘育碧等传统游戏大厂的NFT策略

Express项目创建以及其路由介绍

Nmap and Nikto scanning

15 设计电影租借系统

Express的使用方法,路由的匹配与使用

Uni app wechat applet - Mall (7) - Product Details
随机推荐
Uni app wechat official account (1) - Web page authorization login
05_回顾Object.defineProperty
紅日安全靶場3
金融学 杂项记录
使用redis - zset做排行榜
01_ Template syntax
8 找到和最大的长度为 K 的子序列
Uni app wechat applet - Mall (6) - my home page
数字藏品NFT那个平台好
axs火爆,还有哪些打金游戏(上)
ES6 syntax -- Deconstruction assignment
Timestamp conversion time
03-BTC-协议
元宇宙会给万亿市场的音乐产业带来哪些变化?
Recurrence of yii2 deserialization vulnerability
el-date-picker时间范围控制
二分法查找
13 K 次取反后最大化的数组和
XXX packages are looking for funding run `npm fund` for details解决方法
JS数组常用方法