# 客户端
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 1.获取socket对象
phone.connect(('127.0.0.1', 8080)) # 2.连接服务端端口
data = phone.recv(1024) # 3.接收
while 1:
msg = input()
phone.send(msg.encode('utf-8')) # 发送数据
if not msg: continue # 防止空内容bug
phone.close() # 4.关闭
# 服务端
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 1.获取socket对象
phone.bind(('127.0.0.1', 8080)) # 2.绑定服务端口
phone.listen(5) # 3.等待连接
connect, client_addr = phone.accept() # 4.建立连接并获得连接对象
while 1:
try:
data = connect.recv(1024) # 5.接收数据
if not data: break # 防止客户端单方终止的Linux bug
except ConnectionResetError: # 防止客户端单方终止的windows bug
break
connect.send(data.upper()) # 发送数据
connect.close() # 6. 关闭连接
phone.close() # 7.关机
连续循环通讯
# 客户端
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 1.获取socket对象
phone.connect(('127.0.0.1', 8080)) # 2.连接服务端端口
data = phone.recv(1024) # 3.接收
while 1: # 通信循环
msg = input()
phone.send(msg.encode('utf-8')) # 发送数据
if not msg: continue # 防止空内容bug
phone.close() # 4.关闭
# 服务端
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.bind(('127.0.0.1', 8080))
phone.listen(5) # 当有1个客户端通信阻塞时,其他客户端会被挂起,上限是 5 个
while not close: # 连接循环 可进行多次连接, 但每次只通信一个客户端, 排队服务..
connect, client_addr = phone.accept()
while not disconnect: # 通信循环
try:
data = connect.recv(1024)
if not data: break
except ConnectionResetError:
disconnect = 1
connect.send(data.upper())
connect.close()
phone.close()