我正在尝试与连接到我的计算机的以太网设备建立通信。当我将套接字连接到设备的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(address)“重新连接”时,它告诉我该套接字正在使用中。
感谢您的所有帮助。
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))
### 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')