TCP服务器和客户端的创建(socket/socketserver)

本文详细介绍了Python中使用socket和socketserver模块创建TCP服务器和客户端的方法,包括本地和远程连接交互。内容涵盖了socket的基础知识,如地址格式、创建socket对象,以及socketserver的TCPServer和BaseRequestHandler的使用。
摘要由CSDN通过智能技术生成

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() 
    # 打印请求此次服务的客户端的地
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值