一、一次通信
# server端 v1
import socket
# 1、买手机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# print(phone)
# 2、绑定手机卡
phone.bind(('127.0.0.1', 8081)) # 0-65535:0-1024给操作系统使用
# 3、开机
phone.listen(5) # 最大挂起连接数
# 4、等电话连接
print('starting...')
conn, client_addr = phone.accept()
# 5、收,发消息
data = conn.recv(1024) # 1、单位:bytes 2、1024代表最大接收1024个bytes
print('客户端的数据', data)
conn.send(data.upper())
# 6、挂电话
conn.close()
# 7、关机
phone.close()
# client端 v1
import socket
# 1、买手机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# print(phone)
# 2、拨号
phone.connect(('127.0.0.1', 8081))
# 3、发,收消息
phone.send('hello'.encode('utf-8'))
data = phone.recv(1024)
print(data)
# 4、关闭
phone.close()
二、循环通信
v2.1
# server端 v2.1
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.bind(('127.0.0.1', 8083)) # 0-65535:0-1024给操作系统使用
phone.listen(5)
print('starting...')
conn, client_addr = phone.accept()
print(client_addr)
while True: # 通信循环
data = conn.recv(1024)
print('客户端的数据', data)
conn.send(data.upper())
conn.close()
phone.close()
# client端 v2.1
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8083))
while True:
msg = input('>>: ').strip()
phone.send(msg.encode('utf-8'))
data = phone.recv(1024)
print(data)
phone.close()
v2.2
解决bug
# server端 v2.2
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 系统回收端口需要时间,这里表示如果有端口则直接使用不创建端口
phone.bind(('127.0.0.1', 8083)) # 0-65535:0-1024给操作系统使用
phone.listen(5)
print('starting...')
conn, client_addr = phone.accept()
print(client_addr)
while True: # 通信循环
try:
data = conn.recv(1024)
if not data: break # 适用于linux操作系统
print('客户端的数据', data)
conn.send(data.upper())
except ConnectionResetError: # 适用于windows操作系统
break
conn.close()
phone.close()
# client端 v2.2
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8083))
while True:
msg = input('>>: ').strip() # msg=''
if not msg: continue
phone.send(msg.encode('utf-8')) # phone.send(b'')
# print('has send')
data = phone.recv(1024)
# print('has recv')
print(data.decode('utf-8'))
phone.close()
三、多客户端
可依次对多个客户端进行服务
# server端 v3
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
phone.bind(('127.0.0.1', 8083)) # 0-65535:0-1024给操作系统使用
phone.listen(5)
print('starting...')
while True: # 链接循环
conn, client_addr = phone.accept()
print(client_addr)
while True: # 通信循环
try:
data = conn.recv(1024)
if not data: break # 适用于linux操作系统
print('客户端的数据', data)
conn.send(data.upper())
except ConnectionResetError: # 适用于windows操作系统
break
conn.close()
phone.close()