首页 > 解决方案 > Python套接字错误10054,连接被远程主机中断

问题描述

我正在尝试与连接到我的计算机的以太网设备建立通信。连接似乎工作正常,当我将套接字连接到设备的 IP 地址和端口时,但是当我尝试向设备发送命令时,它返回 [错误 10054 - 连接被远程主机强行中断]。我到目前为止的代码是这样的:

import socket
import time
import logging



logging.basicConfig(filename='conn.txt', filemode='w')


logging.warning('Starting...')
address = ('192.168.1.23', 23)
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


ok = soc.connect_ex(address)


if ok == 0:
    logging.warning('Connected to device ' + str(ok))
else:
    logging.warning('Connection failed ' + str(ok))



### send at command
command = 'AT+SENSOR_IDS'
cmd_to_send = command + '\r\n'
cmd_to_send = cmd_to_send.encode('ascii')
logging.warning('Sending at command')

soc.sendall(cmd_to_send)
logging.warning('at command sent, waiting for echo')


# read echo
echo = soc.recv()
logging.warning('received echo: ' + echo)

print('finished')

当我尝试与另一个 soc.connect_ex(地址)“重新连接”时,它告诉我套接字正在使用中。

谢谢你的帮助。


编辑:

因此,由于缺乏文档,我对该设备知之甚少,因此我决定仅使用 Echo 服务器和本地主机上的客户端示例来模拟问题。我有这个代码:

服务器端:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 1001)
s.bind(server_address)

s.listen(1)

# looking for clients
while True:
    print('waiting for connection')
    connection, client_address = s.accept()
    # when client connects
    try:
        print('Connection from %s port %s' % client_address )

        # get all the data and echo it back
        while True:
            data = connection.recv(15)
            print('Received:   ' + str(data))

            if not data:
                try:
                    s.sendall(data)
                except:
                    print('echoing data failed')
                break

    finally:
        connection.close()

客户端:

import socket

address = ('127.0.0.1', 1001)
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

ok = soc.connect_ex(address)

try:
    if ok == 0:
        print('Connected to device ' + str(ok))
    else:
        print('Connection failed ' + str(ok))
except Exception as e:
    soc.close()
    print("connection not succesful, error returned :", e)

try:
    cmd_to_send = 'AT+SENSOR_IDS\r\n'.encode('ascii')
    bytes_sent = soc.sendall(cmd_to_send)
    if bytes_sent == None:
        print('Command sent succesfully')
    else:
        print('AT command failed to be sent')

    # read echo
    echo = soc.recv()
    print('received echo: ' + echo)
    soc.close()
except:
    try:
        soc.close()
        print('at command or echo reading failed')
    except:
        print('Process finished socket exception occured')

服务器接收到命令后,由于套接字关闭并且不再工作,因此无法将其回显给客户端。如何让插座保持活力?

谢谢您的帮助

标签: pythonsocketsnetworkingtcpethernet

解决方案


您必须关闭您打开的套接字,否则它们将一直打开,直到达到超时。

尝试这个:

import socket
import time
import logging

logging.basicConfig(filename='conn.txt', filemode='w')

logging.warning('Starting...')
address = ('192.168.1.23', 23)
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    ok = soc.connect_ex(address)

    if ok == 0:
        logging.warning('Connected to device ' + str(ok))
    else:
        logging.warning('Connection failed ' + str(ok))
except Exception as e:
    soc.close()
    print("Connection is not successful, error returned :", e)

try:
    ### send at command
    command = 'AT+SENSOR_IDS'
    cmd_to_send = command + '\r\n'
    cmd_to_send = cmd_to_send.encode('ascii')
    logging.warning('Sending at command')

    soc.sendall(cmd_to_send)
    logging.warning('at command sent, waiting for echo')

    # read echo
    echo = soc.recv()
    logging.warning('received echo: ' + echo)
except:
    try:
        soc.close()
        print('Process Finished Succefully')
    except:
        print('Process Finished Socket Exception Occured')


推荐阅读