【Python】Python network programming (Introduction to Socket | Socket usage steps | Socket server and client development)





1. Introduction to Socket




1. Socket concept


Socket socket is a communication mechanism between processes, and data exchange can be performed between different processes through sockets;

insert image description here

In network programming, Socket sockets are mainly used for communication between clients and servers, and most network-related applications use Socket socket technology;


2. Socket socket type


There are two types of sockets:

  • Stream socket: Provides a reliable, connection-oriented communication mechanism that can transmit data sequentially.
    • In the TCP/IP protocol, stream sockets use the TCP protocol for data transmission.
  • Datagram socket: Provides a connectionless, unreliable communication mechanism where data is transmitted in independent packets.
    • In the TCP/IP protocol, the datagram socket uses the UDP protocol for data transmission.

3. Socket socket usage steps


Socket socket usage steps:

  • Create a socket: use the socket API to create a socket object, generally the standard API is provided by the official programming language;
  • Bind IP address and port number: bind the socket with an IP address and port number;
  • establish connection :
    • Server-side monitoring connection: For stream sockets, it is necessary to monitor the client's connection request on the server side;
    • The client establishes a connection: for a stream socket, the client needs to establish a connection with the server;
  • Send and receive data: use Socket to send or receive data;
  • Close the connection: After the data transmission is completed, close the Socket socket connection;

4. Socket server and client


When the Socket socket is used for data communication, two Socket sockets are required as the client and server respectively:

  • Socket socket server side: need to listen to the client's request, can send messages to the client, and can receive messages from the client;
  • Socket socket client: need to actively connect to the server, can send messages to the server, and can receive messages from the server;

A server can interact with multiple clients at the same time;





2. Socket server and client development




1. Server


Socket server-side process:

  • Create a socket: use the socket API to create a socket object, generally the standard API is provided by the official programming language;
# 1. 创建 socket 实例对象
import time
  • Bind IP address and port number: bind the socket with an IP address and port number;
# 2. 为 socket 实例对象 绑定 IP 地址和端口号
# IP 地址是字符串类型, 端口号是 int 类型, 将这两个数据定义到元组中
socket_server.bind(("127.0.0.1", 8090))
  • Server-side monitoring connection: For stream sockets, it is necessary to monitor the client's connection request on the server side;
    # 4. 阻塞等待连接 , 如果没有客户端连接 , 会一直阻塞在这里
    # accept 函数返回的是 二元元组 , 使用两个变量接收该元组
    # conn 是连接的 socket 对象
    # address 是连接的 地址
    client_socket, client_address = socket_server.accept()
  • Send and receive data: use Socket to send or receive data;
    # 向客户端发送连接成功提示
    client_socket.send("你好, 客户端!".encode("UTF-8"))
  • Close the connection: After the data transmission is completed, close the Socket socket connection;
    # 关闭连接
    client_socket.close()

Code example:

"""
Socket 服务器 代码示例
"""

# 导入 socket 模块
import socket

# 1. 创建 socket 实例对象
import time

socket_server = socket.socket()

# 2. 为 socket 实例对象 绑定 IP 地址和端口号
# IP 地址是字符串类型, 端口号是 int 类型, 将这两个数据定义到元组中
socket_server.bind(("127.0.0.1", 8090))

# 3. 服务器端监听端口
# 传入的参数是一个整数 , 该参数表示允许连接的数量
# 如果连接已满后面的连接请求会等待
socket_server.listen(100)


while True:
    # 4. 阻塞等待连接 , 如果没有客户端连接 , 会一直阻塞在这里
    # accept 函数返回的是 二元元组 , 使用两个变量接收该元组
    # conn 是连接的 socket 对象
    # address 是连接的 地址
    client_socket, client_address = socket_server.accept()

    # 向客户端发送连接成功提示
    client_socket.send("你好, 客户端!".encode("UTF-8"))
    print(f'客户端连接成功 {
      
      client_address}')

    # 5. 服务器端与客户端进行交互
    while True:
        # 循环接收客户端数据, 并使用 UTF-8 解码
        data = client_socket.recv(1024).decode("UTF-8")

        # 向客户端会送消息
        client_socket.send(f"服务端已收到: {
      
      data}".encode())
        print(f"客户端: {
      
      data}")

        if data == 'quit':
            break

    # 关闭连接
    client_socket.close()
    print(f'客户端连接关闭 {
      
      client_address}')

2. Client


Socket client process:

  • Create a socket: use the socket API to create a socket object, generally the standard API is provided by the official programming language;
# 1. 创建 socket 实例对象
client_socket = socket.socket()
  • Connect to the server by IP address and port number:
# 2. 客户端连接服务器, IP 地址和端口号放在元组中
client_socket.connect(('127.0.0.1', 8090))
  • Send and receive data: use Socket to send or receive data;
# 发送数据到服务器
client_socket.send('你好, 服务器!'.encode())
  • Close the connection: After the data transmission is completed, close the Socket socket connection;
# 4. 关闭连接
client_socket.close()

Code example:

import socket

# 创建TCP socket对象
import time

# 1. 创建 socket 实例对象
client_socket = socket.socket()

# 2. 客户端连接服务器, IP 地址和端口号放在元组中
client_socket.connect(('127.0.0.1', 8090))

# 3. 向服务器端发送消息和接收消息
# 发送数据到服务器
client_socket.send('你好, 服务器!'.encode())
print("客户端发送: 你好, 服务器!")

time.sleep(1)
# 接收服务器数据
data = client_socket.recv(1024).decode("UTF-8")
print(f"服务端: {
      
      data}")

# 获取命令行输入发送给客户端
while True:
    command = input("请输入: ")
    client_socket.send(command.encode())
    print(f"客户端发送: {
      
      command}")
    if command == 'quit':
        break

    # 接收服务器数据
    data = client_socket.recv(1024).decode("UTF-8")
    print(f"服务端: {
      
      data}")

# 4. 关闭连接
client_socket.close()
print("客户端关闭")


3. Execution results


Start the server first:

insert image description here

Start the client:
insert image description here
At this time, the information on the server is as follows:
insert image description here
client interrupt input 1:

insert image description here
Server-side effects:
insert image description here

The client continues to input information:
insert image description here
the server-side information is as follows:
insert image description here

The client enters quit to close the connection:

insert image description here

Corresponding data on the server side:

insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/131967671