Python线程套接字/OS/Win错误线程中未处理的异常

2024-03-28 10:00:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个python程序,一旦启动,它将主动侦听传入连接(通过socket),但也为用户提供启动传出连接的机会。这是我的目标计划的基本描述,我在这里稍微详细一点。。。 python - stop waiting for input() when a condition (not timer) is met

我仍然没有找到解决我在上面的链接中提出的问题的方法。不过,我已经稍微改变了方向,并一直在这个项目的功能方面的工作。我已经取得了进展,我有一个接收连接请求和发送连接请求程序的工作解决方案

发送连接请求时,程序将成功连接,但会引发错误

Unhandled exception in thread started by <function outgoing at 0x00E4D4B0>
Traceback (most recent call last):
  File "PATH\program.py", line 27, in outgoing
    sc.connect((ip, port))
OSError: [WinError 10022] An invalid argument was supplied

即使抛出此错误,我仍然成功地连接到服务器/主机

这个程序还远远没有完成,我知道还有很多改进要做,但现在我只是想得到一个工作/无错误的解决方案

import socket
from _thread import *

ip = ''
host = ''
port = 5555

ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    ss.bind((host, port))
except socket.error as e:
    print(str(e))

ss.listen(2)

def incoming():
        conn, addr = ss.accept()
        if conn:
            print('################################\nIncoming Connection Established!\n Address = '+addr[0]+':'+str(addr[1]))

def outgoing():
    while True:
        if ip != '':
            try:
                sc.connect((ip, port))
                break
            except error as e:
                print(str(e))
                break

print("Waiting for a connection...")

start_new_thread(incoming,())
start_new_thread(outgoing,())

ip = input('...Or enter an ip address to initiate the connection.\n')

outgoing()

Tags: 程序ipforinputport错误socket解决方案