18. python from beginner to proficient - network programming

Table of contents

Create Socket

Socket communication process

Common methods of Socket objects

TCP programming

Example: Use the server to send to the browser: Hellow Word

Create TCP server

Create TCP client

Server and client interaction

UDP programming

Application scenarios

Example: Convert Celsius to Fahrenheit

Create UDP server

Basic model of UDP communication


Socket: Provides an interface for programs to connect to external processes. It is an encapsulation of the underlying protocol. According to different underlying protocols, the implementation of Socket is diverse. Each socket must be bound to a port number and IP

Advantages: When programming in python, you do not need to consider the specific implementation of network protocols such as three-way handshakes. You can directly implement it through the Socket object.

Create Socket

grammar:

        s = socket.socket(AddressFamily, Type)

                #Address Family: You can choose AF_INET (for Internet inter-process communication) or AF_UNIX (for inter-process communication on the same machine). AF_INET is commonly used in actual work.

                #Type: Socket type, which can be SOCK_STREAM (streaming socket, mainly used for TCP protocol) or SOCK_DGRAM (datagram socket, mainly used for UDP protocol)

Socket communication process

Based on the TCP protocol as an example: First, both the client and the server need to create a Socket.

        server:

                Socket(): Create Socket

                Bind(): Bind IP and port number

                Listen(): listening port

                Accept(): Waiting to receive

                Receive(): receive data

                Send(): function sends data

                Close(): Close Socket

        client:

                Socket(): Create Socket

                Connet(): Connect to the server's Accept() function corresponding to the server. The three-way handshake is completed in this process.

                Send(): function sends data

                Receive(): receive data

                Close(): Close Socket

Common methods of Socket objects

method name

describe

s.bind()

Bind the address (host, port) to the socket. Under AF_INET, the address is expressed in the form of a tuple (host, port).

s.listen()

Start TCP listening. The backlog specifies the maximum number of connections the operating system can suspend before rejecting the connection. This value should be at least 1, and 5 will be fine for most applications.

s.accept()

Passively accept TCP client connections and (blocking) wait for the arrival of the connection

s.connect()

Actively initialize the TCP server connection. Generally, the format of address is a tuple (hostname, port). If a connection error occurs, a socket.error error is returned.

s.recv()

Receive TCP data, the data is returned in the form of a string , bufsize specifies the maximum amount of data to be received. flag provides additional information about the message and can usually be ignored.

s.send()

Send TCP data, sending the data in a string to the connected socket. The return value is the number of bytes to send, which may be less than the string's byte size.

s.sendall()

Send TCP data completely. Sends the data in a string to the connected socket, but attempts to send all data before returning. Returns None on success, throws an exception on failure.

s.recvfrom()

Receive UDP data, similar to recv(), but the return value is a tuple (data, address) . Where data is a string containing the received data, and address is the socket address to which the data is sent.

s.sendto()

Send UDP data to a socket, where address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent.

s.close()

close socket

TCP programming

Example: Use the server to send to the browser: Hellow Word

Create TCP server

# -*- coding:utf-8 -*-
import socket               #导入socket模块
host = '127.0.0.1'          #主机IP
port = 8080                     #端口号
web = socket.socket()           #创建 socket 对象
web.bind((host,port))       #绑定端口
web.listen(5)               #设置最多连接数
print ('服务器等待客户端连接...') 
#开启死循环
while True:
    conn,addr = web.accept()    #建立客户端连接:conn是一个新的Socket对象,addr是连接客户端的IP地址
    data = conn.recv(1024).decode()      #获取客户端请求数据,decode()指定解码格式
    print(data)             #打印接受数据
    conn.sendall(b'HTTP/1.1 200 OK\r\n\r\nHello World')     #向客户端发送数据
    conn.close()            #关闭链接 
#############
##服务器等待客户端连接...
##hi

verify:

        Start this program from the command line

        Browser access: 127.0.0.1:8080

Create TCP client

import socket       # 导入socket模块
s= socket.socket()  # 创建TCP/IP套接字
host = '127.0.0.1'  # 获取主机地址
port = 8081        # 设置端口号
s.connect((host,port)) # 主动初始化TCP服务器连接

send_data = input("请输入要发送的数据:") # 提示用户输入数据
s.send(send_data.encode()) # 发送TCP数据,encode():指定编码格式

# 接收对方发送过来的数据,最大接收1024个字节
recvData = s.recv(1024).decode() #encode():指定解码格式
print('接收到的数据为:',recvData)

# 关闭套接字
s.close()
##############################
##请输入要发送的数据:hi
##接收到的数据为: HTTP/1.1 200 OK

##Hello World

Verification: The command line executes the server program first and then the client program.

Server and client interaction

Example: Making a simple chat window

Implementation: The content sent by the client is printed on the server, and the content sent by the server is printed on the client. Terminal connection when typing baibai

Server code:

import socket               # 导入socket模块
host = socket.gethostname() # 获取主机地址
port = 12345                # 设置端口号   
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #创建TCP/IP套接字
s.bind((host,port)) # 绑定地址(host,port)到套接字
s.listen(1) # 设置最多连接数量
sock,addr = s.accept() # 被动接受TCP客户端连接
print('连接已经建立') 
info = sock.recv(1024).decode() # 接收客户端数据
while info != 'byebye':  # 判断是否退出
  if info : #判断是否有内容
    print('接收到的内容:'+info)
  send_data = input('输入发送内容:')   # 发送消息
  sock.send(send_data.encode()) # 发送TCP数据
  if send_data =='byebye':  # 如果发送exit,则退出
    break
  info = sock.recv(1024).decode() # 接收客户端数据
sock.close() # 关闭客户端套接字
s.close()    # 关闭服务器端套接字

Client code:

import socket       # 导入socket模块
s= socket.socket()  # 创建TCP/IP套接字
host = socket.gethostname() # 获取主机地址
port = 12345        # 设置端口号     
s.connect((host,port)) # 主动初始化TCP服务器连接
print('已连接')
info = ''           
while info != 'byebye':  # 判断是否退出
  send_data=input('输入发送内容:')    # 输入内容
  s.send(send_data.encode()) # 发送TCP数据
  if send_data =='byebye': # 判断是否退出
    break
  info = s.recv(1024).decode() # 接收服务器端数据
  print('接收到的内容:'+info)
s.close() # 关闭套接字

verify:

UDP programming

Application scenarios

Voice broadcast
video
chat software
TFTP (trivial file transfer)
SNMP (simple network management protocol)
RIP (routing information protocol, such as reporting stock market, aviation information)
DNS (domain name interpretation)

Example: Convert Celsius to Fahrenheit

Create UDP server

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #创建UDP套接字
s.bind(('127.0.0.1', 8888)) # 绑定地址(host,port)到套接字
print('绑定UDP到8888端口')
# 接收数据:最大接受1024字节
data, addr = s.recvfrom(1024) 
data = float(data)*1.8 + 32 # 转化公式
send_data = '转换后的温度(单位:华氏温度):'+str(data)
print('Received from %s:%s.' % addr)
s.sendto(send_data.encode(), addr) # 发送给客户端
s.close()    # 关闭服务器端套接字

Validation results

Basic model of UDP communication

Guess you like

Origin blog.csdn.net/weixin_43812198/article/details/132039298