Socket family based on network type
Socket family name: AF_INET
(Also AF_INET6 is used for ipv6. Among all address families, AF_INET is the most widely used one. Python supports many address families, but since we only care about network programming, most of the time we only use AF_INET)
Working process of socket based on TCP
Client
socket ()-instantiate a socket object
When the client sends data to the outside, it needs to transfer the transport layer and the transport layer uses the TCP protocol to establish the connection first.
Below the application layer are all under the socket management, so use the socket to connect () to establish a connection
Three things happen when establishing a connection: three handshake
send () —— Send data to server
close ()-close the connection
Server
socket ()-instantiate a socket object
bind ()-bind IP and port
listen-listen for connection requests
accept () —— retrieve the request from the semi-connection pool and start to return the packet ps: did three handshake with connact
close ()-close the connection
Based on TCP protocol
Server
import socket
# 1.买手机
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #流式协议=》TCP协议
# 2.绑定手机
phone.bind(('127.0.0.1',8080))
# 3.开机
phone.listen(5) # 半连接池得大小
print('服务端启动完成,监听地址为:%s%s' %('127.0.0.1',8080)) #127.0.0.1 本地回环地址
# 4.等待电话连接请求
# 加上链接循环
while True:
conn,client_addr=phone.accept()
print('客户端的ip和端口:',client_addr)
# 5.通信收、发消息
while True:
try:
data=conn.recv(1024) # 最大接收得数据量为1024Bytes,收到得是bytes类型
if len(data)==0:break
print('客户端发来的消息:',data.decode('utf-8'))
conn.send(data.upper())
except Exception:
break
# 6.关闭电话连接conn
conn.close()
Client
import socket
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))
import time
time.sleep(5)
while True:
msg = input('请输入======>').strip()
if len(msg) == 0: continue
phone.send(msg.encode('utf-8'))
data=phone.recv(1024)
print(data.decode('utf-8'))
phone.close()
Based on UDP protocol
Server
import socket
server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #流式协议=》TCP协议
server.bind(('127.0.0.1',8080))
while True:
data,client_addr=server.recvfrom(1024)
print(data.upper(),client_addr)
server.close()
Client
import socket
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
msg = input('请输入======>').strip()
client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
data,server_addr=client.recvfrom(1024)
print(data.decode('utf-8'))
client.close()