python socket连接放在循环内为什么只有第一次执行了?
我写了一个demo测试一下python的socket用法.
客户端有个循环, 我的socket连接和close写在循环体外面没有问题, 但写在循环内服务器却提示只收到了第一次的请求
代码如下:
server.py
#!/usr/bin/env python3import socket
import time
HOST = '127.0.0.1' # 标准的回环地址 (localhost)
PORT = 65432 # 监听的端口 (非系统级的端口: 大于 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print(111)
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if data:
print('receive: ', data)
conn.sendall(b'1')
time.sleep(1)
conn.sendall(b'2')
time.sleep(1)
conn.sendall(b'3')
client.py
#!/usr/bin/env python3import socket
# SOCKET连接在循环体外
# sendData = [
# 'aaaaaaaaaaaaaaaaa',
# 'bbbbbbbbbbbbbbbbbbbbbbbbb',
# 'ccccccccccccccccccccccc'
# ]
# HOST = '127.0.0.1' # 服务器的主机名或者 IP 地址
# PORT = 65432 # 服务器使用的端口
# sk = socket.socket()
# sk.connect((HOST, PORT))
# print('conn success')
# for d in sendData:
# print('current:', d)
# sk.sendall(bytes(d, encoding='utf-8'))
# print('sent')
# while True:
# server_reponse = sk.recv(2048)
# if (server_reponse):
# recData = str(server_reponse, encoding='utf-8')
# print('Received', recData)
# if recData == '3':
# print('===================')
# break
# sk.close()
# print('conn closed')
# SOCKET连接在循环体内
sendData = [
'aaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccccccc'
]
HOST = '127.0.0.1' # 服务器的主机名或者 IP 地址
PORT = 65432 # 服务器使用的端口
for d in sendData:
sk = socket.socket()
sk.connect((HOST, PORT))
print('conn success')
print('current:', d)
sk.sendall(bytes(d, encoding='utf-8'))
print('sent')
while True:
server_reponse = sk.recv(2048)
if (server_reponse):
recData = str(server_reponse, encoding='utf-8')
print('Received', recData)
if recData == '3':
sk.close()
print('conn closed')
print('===================')
break
以上是 python socket连接放在循环内为什么只有第一次执行了? 的全部内容, 来源链接: utcz.com/p/939023.html