1 本文记录针对python网络编程学习过程中的socket部分进行记录与总结,内容仅仅涉及最粗浅的部分,日后或许会进行更新与扩展。
2 本文涉及的socket数据传输均使用bytes类型,因此在python3环境下,需要特别注意字符串的编码与解码。
1 socket模块
A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like ‘daring.cwi.nl’ or an IPv4 address like ‘100.50.200.5’, and port is an integer.
For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents INADDR_ANY, and the string ‘’ represents INADDR_BROADCAST. This behavior is not compatible with IPv6, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.
- 创建socket对象,
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None) - 根据官方文档说明,socket接受两种特殊形式的IPv4的地址。空白地址代表
INADDR_ANY,允许任意地址接入;而字符串’<broadcast>’则代表INADDR_BROADCAST。
1.1 创建TCP服务器 - socket.socket()
from socket import *
from time import ctime
HOST = '' # 允许任意host接入
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR) # 绑定地址
tcpSerSock.listen(5) # 最多同时监听数量上限为5
while True:
print('waiting for connection...')
# 接受客户端请求之前保持阻塞,连接后获取客户端socket及其地址
tcpCliSock, addr = tcpSerSock.accept()
# 打印请求此次服务的客户端的地

本文详细介绍了Python中使用socket和socketserver模块创建TCP服务器和客户端的方法,包括本地和远程连接交互。内容涵盖了socket的基础知识,如地址格式、创建socket对象,以及socketserver的TCPServer和BaseRequestHandler的使用。
最低0.47元/天 解锁文章
802

被折叠的 条评论
为什么被折叠?



