Simple use of socket in Python network programming

Article Directory

1 Introduction

Python provides two levels of services:

  1. Socket (low level)
  2. SocketServer (high level)

What is Socket? Commonly known as "socket", an abstraction of the TCP protocol, it can be used for communication between hosts or between processes.

First, use a simple example to understand the basic steps of socket creation, connection, and communication. The basic steps on the server side:

  1. Bind hostname, port
  2. Use the accept method to wait
  3. Send the message to the client

# 引入模块
import socket
import sys


# 创建socket对象,套接字家族选用AF_INET,套接字类型选用面向连接。
server_socket = socket.socket(
    family=socket.AF_INET,
    type=socket.SOCK_STREAM
)


# 获取本机主机名:MacBook-Pro.local
host = socket.gethostname()
port = 9999


# 绑定端口号
server_socket.bind((host, port))


# 设置最大连接数,超过后排队
server_socket.listen(5)


while True:
    # 建立客户端连接
    client_socket, addr = server_socket.accept()
    print(f'连接地址:{addr}')


    message = 'Hello world, socket!'
    client_socket.send(
        message.encode('UTF-8')
    )
    client_socket.close()

The basic steps on the client side:

  1. Specify hostname and port to connect to the service
  2. Accept message

import socket
import sys


# 创建socket对象
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)


# 获取本机名,设置端口号
hostname = socket.gethostname()
port = 9999


# 连接到服务
s.connect(
    (hostname, port)
)


# 接受消息
message = s.recv(1024)
print(message.decode('UTF-8'))

2 ports

A socket is just a hub for the user program and the kernel to interact with information. It does not have much information, nor does it have a network protocol and port number. During network communication, a socket must be associated with an address. This process is the process of address binding.

In many cases, the kernel will automatically bind an address, but in many cases it will be manually bound for the convenience of memory and management. The most typical situation is that the server process binds a port and waits for other processes to connect.

The following is a simple verification, the server-side code:


# 引入模块
import socket
import sys


# 创建socket对象,套接字家族选用AF_INET,套接字类型选用面向连接。
server_socket = socket.socket(
    family=socket.AF_INET,
    type=socket.SOCK_STREAM
)


# 获取本机主机名:MacBook-Pro.local
host = socket.gethostname()
port = 9999


# 绑定端口号
server_socket.bind((host, port))


# 设置最大连接数,超过后排队
server_socket.listen(5)


count = 0
while True:
    # 建立客户端连接
    client_socket, addr = server_socket.accept()
    count += 1
    print(f'连接地址:{addr}')
    print(count)


    message = 'Hello world, socket!'
    client_socket.send(
        message.encode('UTF-8')
    )
    client_socket.close()

After each connection, the IP and port of the other party will be output, so that the changes of the port can be observed more clearly.

client side (unbound fixed port)


import socket
import sys


# 创建socket对象
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)


# 获取本机名,设置端口号
hostname = socket.gethostname()
port = 9999


# 连接到服务
s.connect(
    (hostname, port)
)


# 接受消息
message = s.recv(1024)
print(message.decode('UTF-8'))

First start the server side, and then start the client side, you can see the client side echo the following letters: Hello world, socket!

After several runs, it is clear that the port of client.py is changing, indicating that its port is automatically allocated by the system.

You can consider binding the port manually to fix the ip port to the port you want, and execute the following code before connecting.



s.bind(
    (hostname, 59446)
)

The final code is:



import socket
import sys


# 创建socket对象
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)


# 获取本机名,设置端口号
hostname = socket.gethostname()
port = 9999


# 连接到服务
s.bind(
    (hostname, 59446)
)
s.connect(
    (hostname, port)
)


# 接受消息
message = s.recv(1024)
print(message.decode('UTF-8'))

You can find that after you manually bind the port, the port is fixed

The result is as mentioned above, if the port is not bound, the system will automatically allocate the port.

appendix

Reference tutorial:

  1. Python3 network programming: https://www.runoob.com/python3/python3-socket.html
  2. Bind function of network programming socket: https://blog.csdn.net/dongliqiang2006/article/details/5824651

Guess you like

Origin blog.csdn.net/qq_43085611/article/details/112991052