python network connection (udp and tcp)

Go straight to the topic

udp connection

There is no clear difference between the server and the client for this connection. In fact, a user can be either a server or a client. Socket is used to complete network programming in python. The
specific code is as follows:

Client

    #socket.AF_INET 是建立连接 socket.SOCK_DGRAM 是使用UDP链接
    s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    id = socket.gethostbyname(socket.gethostname()).split(":")[0]

    s.sendto('hello'.encode('utf'),(id,8088))
    s.close()
    print("发送成功!!!!")

Server

    s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    id = socket.gethostbyname(socket.gethostname()).split(":")[0]

    s.bind((id,8088))
    print('准备接收中')
    data=s.recvfrom(1024)
    print("%s"%(data[0].decode('utf')))

The following is an explanation: The
gethostbyname() method can get the IP address of the current host (in the local area network).
Recvfrom() is the receiving information. This is the method
that is received from the client and this is a blocking method. The method returns two values, one is binary Data, the other is the sender's IP and port
bind() is to bind the IP and port, which needs to be used when receiving data

TCP connection

The difference between tcp and udp is that tcp needs to be connected to the server first. The advantage of this is that it can ensure the security of data transmission. udp is only sent without guaranteeing the connection, which is prone to problems.
The following is An example:
client:

    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    id = socket.gethostbyname(socket.gethostname()).split(":")[0]
    s.connect((id,8089))
    s.send('hello'.encode('utf8'))
    print("数据发送完成")
    tes=s.recv(1024)
    print(tes.decode('utf8'))
    s.close()

Server

    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    id = socket.gethostbyname(socket.gethostname()).split(":")[0]
    s.bind((id,8089))
    print("TCP服务器开启")
    s.listen(128)
    data,ip_where=s.accept()
    print(data.recv(1024).decode('utf8'))
    data.send('world'.encode('utf8'))

Explanation:
On the server side, we use accept() to receive data
and return two values, one is the sender's socket, which means that we can directly use this to accept the sender's data and send data to him, and the second one is It is the sender's IP and port
lsten() This is the maximum number of connections that the server can exceed the pressure, setting 128 here means that it can overload 128 connections at most.
Insert picture description here

Practice actual combat, file download server

Taking into account the security of downloading, there is no accident that we use tcp to connect
client

import socket

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
id = socket.gethostbyname(socket.gethostname()).split(":")[0]
s.connect((id,8089))

filename = str(input("输入您要下载的音乐:"))
s.send(filename.encode('utf-8'))

data = s.recv(1024)

try:
    data.decode("utf-8")
    print("文件不存在")
except :
    #由于是在同一台电脑上为了做出区别下载的文件名字前面会加"下载的"
    with open("下载的"+filename,'wb') as file:
        file.write(data)
        while True:
            data=s.recv(1024)
            if data:
                file.write(data)
            else:
                print("下载完成")
                break

Server:

import socket
import os

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
id = socket.gethostbyname(socket.gethostname()).split(":")[0]
s.bind((id,8089))
s.listen(128)
print("服务器启动")
client = s.accept()[0]
filename = client.recv(1024).decode("utf-8")
if os.path.isfile(filename):

    with open(filename,'rb') as file:
        content = file.read()
        client.send(content)
        print("文件发送完成")
else:

    client.send("文件不存在".encode('utf-8'))

Insert picture description here
Very fast, almost instantaneous

Guess you like

Origin blog.csdn.net/FUTEROX/article/details/112375277