更新时间:2022-09-07 23:26:28
开发者学堂课程【Python网络编程:TCPServer 简单实现流程】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/602/detail/8777
内容介绍:
一、复习与回顾
二、实际操作
(1)Socket套接字
Python 中提供 socket.py 标准库,非常底层的接口库。
Socket 是一种通用的网络编程接口,和网络层次没有——对应的关系。
协议族
AF 表示 Address Family,用于 socket()第一个参数
Socket (计算机专业术语)
网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个 socket , Socket 的英文原义是"孔"或"插座"。作为 BSD UNIX 的进程通信机制,取后一种意思。通常也称作"套接字",用于描述 IP 地址和端口,是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。在 Internet 上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个 Socket,并绑定到一个端口上,不同的端口对应于不同的服务。
名称 |
含义 |
AF_INET |
IPV4 |
AF_INET6 |
IPV6 |
AF_UNIX |
Unix Domain Socket,Windows没有 |
(2)Socket 类型
名称 |
含义 |
SOCK_STREAM |
面向连接的流套接字、默认值,TCP协议 |
SOCK_DGRAM |
无连接的数据报文套接字。UDP协议 |
Import socket
server = socket.socket ()
server
<socket.socket fd=12,family=AddressFamily.AF_INET,type=SocketKind.SOCK_ STREAM,proto=0,laddr=('0.0.0.0',0)>
server.bind?
Docstring:
bind (address)
Bind the socket to a local address. For IP sockets,the address is a pair (host,port); the host must refer to the local host. For raw packet sockets the address is a tuple (ifname,proto [,pkttype [, hatype]])
Type: builtin_function_or_method
ipaddr =('127.0.0.1',9999)
server.bind(ipaddr)
!ss -tanl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 :::22 :::*
LISTEN 0 128 *:22 *:*
LISTEN 0 128 ::1:25 :::*
LISTEN 0 128 127.0.0.1:25 *:*
server.listen()
!ss -tanl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.1:9999 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 128 *:22 *:*
LISTEN 0 128 ::1:25 :::*
LISTEN 0 128 127.0.0.1:25 *:*
server.close()
!ss -tanl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 :::22 :::*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 ::1:25 :::*
LISTEN 0 100 127.0.0.1:25 *:*
server = socket.socket()
server.bind(ipaddr)
server.bind(('0.0.0.0',9999))
OSError Traceback (most recent call last)
<ipython-input-14-f5b3714d4bfe>in <module>
server bind
[Errno 22] Invalid argument