文章目录

  • 前言
  • 一、套接字接口
  • 二、UDP套接字编程
    • 1.特点
    • 2.UDP发送方(客户)编程
    • 3.UDP接收方(服务器)编程
  • 三、TCP套接字编程
    • 1.特点
    • 2.TCP发送方(客户)编程
    • 3.TCP接收方(服务器)编程
  • 四.实现结果
    • 1.UDP运行结果
    • 2.TCP运行结果
    • 3.注意事项
  • 总结

前言

了解了CDNafter the operation process,Learned a little about it hereTCP与UDP的编程,Implement simple server-to-host communication,A deeper understanding of how application-layer network programs work,This article is about the client-Server mode is usedpython来进行编程的,python版本号为3.8.


提示:以下是本篇文章正文内容

一、套接字接口

首先我们了解到,All data packets are read and written through a socket interface,Think of socket interfaces as “门”,而 The message segment that needs to be sent is regarded as the courier you want to send,After we have written the address and information for accepting the courier,Hand it over to the courier outside the door,And the postman goes through a series of journeys(Analogy to linkor路由器),The courier takes the courier to the recipient’s community,The recipient’s doorstep,The courier knocked on the door,The recipient opens the door,拿到快递(Also got the sender(你)address and various types of information),而接收方的“门”Also a socket interface,Sockets have corresponding port numbers,The role of the port number is also to find a specific door with this service(Analogy to the recipient’s door,Others in the community do not receive couriers),At this point you should have a general understanding of how data is transferred and what the socket interface does.

二、UDP套接字编程

1.特点

首先我们知道,UDP是不面向连接的(这里与TCP进行一个对比,can be seen in Chapter 3),So no advance communication handshake,A stable transmission channel is not established,在使用UDP传输的过程中,The hostname of the server must be specified(或者是ip地址)、The port number is attached to the data you want to transfer,The Internet will go through the sender’s socket interface,Send the data set,When the packet arrives at the receiver socket interface,The receiving process recycles the data packets through the socket interface,并对数据进行一系列处理,Then send it through the receiver’s socket interface(注意:When sending here, the sender should also be attachedIP地址和端口号),The sender’s port number has an advantage,不用自己设置,This is left to the operating system to do.

2.UDP发送方(客户)编程

下面是UDP发送方(客户)—接收方(服务器)编译代码:

from socket import *serverName = "hostname" #Here is the receiver(服务器)的主机名,也可以写IP地址serverPost = 48000 #这里是端口号,与接收方(服务器)The programming definition needs to be consistentclientSocket = socket(AF_INET, SOCK_DGRAM) #Here is the definition of a sender(客户)socket interfaceAF_INET是按照IPV4发送,SOCK_DGRAMThis is the definition toUDP发送message = input('Enter the lowercase letters you want to send:') #Here is the definition record the letters entered by the user are assigned tomessageclientSocket.sendto(message.encode(), (serverName, serverPost))#The sender is used here(客户)socket interface to send,必须将message的内容encode,Convert to byte type and send,and append the receiver(The server's hostname and IP地址)modifiedMessage, serveName = clientSocket.recvfrom(2048) #This will receive the modified information from the server through the client's socket interface.print(modifiedMessage.decode()) #解码后打印clientSocket.close() #关闭端口

3.UDP接收方(服务器)编程

代码如下:

from socket import *serverPort = 48000 #The receiver port number setting is the same as the sender port numberserverSocket = socket(AF_INET, SOCK_DGRAM)serverSocket.bind(('', serverPort)) #Associate the port with the receiver(服务器)Socket interface bindingsprint("This server is already")while True: #Keep the server process running all the timemessage, clientAddress = serverSocket.recvfrom(2048) #The data sent by the sender is received through the server socket interfacemodifiedMessage = message.decode().upper() #Capitalize these lettersserverSocket.sendto(modifiedMessage.encode(), clientAddress) #Send the modified letter to the client.

这里需注意一点,For the setting of the port number, avoid the port of the service that has been occupied at this stage.

三、TCP套接字编程

1.特点

TCP是面向连接的,与UDPThere is a very, very big difference,When the sender sends a data group,Now with the recipient(服务器)进行建立TCP通道(三次握手),After the channel is established,There is no need to attach the host name and port number of the server when sending the data group,The data sent back by the server can also be accepted during the re-sending process,而且TCPis to provide reliable data transmissionUDP不保证.

与UDP编程不同的是,TCPThe server has two socket interfaces(形象化),One is the welcome socket and the connection socket,Socket bindings are welcome hereUDPServer programming sockets will be easier to understand,And the connection socket is,TCPThe server welcomes the socket at the same time that it receives the sender’s connect signal,Create a new socket this is called a connection socket,All subsequent data transfers are performed by the connection socket,Visually see the welcome socket as the foreground,You want to solve a problem,打电话到前台,It provides a forwarding phone number,Transfer a new docked staff member,Connect with the problem you need to solve.

2.TCP发送方(客户)编程

代码如下:

from socket import *serverName = "hostname"serverPort = 48000clientSocket = socket(AF_INET, SOCK_STREAM) #The first four lines are withUDPClient programming is the same,只是这里的SOCK_STREAM是TCP连接clientSocket.connect((serverName, serverPort)) #Do one to the serverTCP连接message = input('Please input lowercase sentence:')clientSocket.send(message.encode()) #Note that there is no need to add the address and port number of the server here,直接发送即可modifiedMessage = clientSocket.recv(2048)print("The modified message is:", modifiedMessage.decode())clientSocket.close()

3.TCP接收方(服务器)编程

代码如下:

from socket import *ServerPort = 48000ServerSocket = socket(AF_INET, SOCK_STREAM)ServerSocket.bind(('', ServerPort))#The first few lines are with UDPServer programming is consistent,除了SOCK_STREAM是TCP连接的ServerSocket.listen(1)#At least one user is welcome to do soTCP连接print("The Server Is Already")while True:connectionSocket, addr = ServerSocket.accept()#Respond to user connections using a connection socketmessage = connectionSocket.recv(2048)#Use the connection socket interface to receive data from the sendermodifiedMessage = message.decode().upper()connectionSocket.send(modifiedMessage.encode())connectionSocket.close()#Close this one connection socket

四.实现结果

1.UDP运行结果

2.TCP运行结果

3.注意事项

Here I am doing this little experiment,In theory a computer is required to run as a server segmentUDP/TCP接收方(服务器)的代码,And another computer asUDP/TCP发送方(客户)运行代码,But it is also possible to actually use a computer,运行一个虚拟机,Run different code on each side separately,Or even simpler(我现在使用的方法),使用pycharmRun both codes in parallel, respectively,都是可以的(But the hostname must write the hostname of your computer),How to check the hostname of your computer,是先win+R,输入cmd,再输入hostname,Your hostname is out,on the codehostnameanywhere.


总结

This is the final section of Chapter 2, Application Layers, of this book,through two small experiments,to end the study of this chapter,更加理解了TCP和UDPspecific operating procedures,Of course, more data processing content can also be compiled on the server,More effects can be achieved,This experiment is to send lowercase letters to the server,The server returns an experiment in capital letters,适合初学者,当然C、JAVA都可以编译.