我正在尝试连接到一个 IP 并监听该端口。我不断收到此错误消息
OSError: [WinError 10049] The requested address is not valid in its context
当我使用本地 IP(127.0.0.1) 时它可以工作,为什么现在不能工作?我还可以 ping 通我想要访问的 IP 和端口。这是完整的错误消息。
Traceback (most recent call last): File "C:\Users\rcouillard\listen.py", line 93, in <module> receive_data() File "C:\Users\rcouillard\listen.py", line 58, in receive_data server_socket.bind(server_address) OSError: [WinError 10049] The requested address is not valid in its context
import socket
import mysql.connector
import os
import logging
from datetime import datetime
# Configure logging
log_directory = "C:/logs/"
if not os.path.exists(log_directory):
os.makedirs(log_directory)
log_filename = datetime.now().strftime("%Y-%m-%d\_%H-%M-%S") + "\_sanilog.txt"
log_file_path = os.path.join(log_directory, log_filename)
logging.basicConfig(filename=log_file_path, level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')
# Function to create a connection to the MySQL database
def create_connection():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="saniscalesample"
)
return conn
# Function to insert data into the database
def insert_data(conn, raw_data, connection, reply_port=10001):
data = raw_data.replace("TRANSACTION=", "")
data = data.replace("\<lf\>", "").replace("\<cr\>", "")
data_parts = \[part for part in data.split(";") if part.strip()\]
cursor = conn.cursor()
query = """INSERT INTO truckweigh (trans_num, trans_type, truck_num, weight_kg, weight_lbs, weights_t, weight_man, weight_date, in_num, tare_kg, tare_lbs, tare_t, tare_man, tare_date, net_kg, net_lbs, net_t, net_date, legal_state)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
cursor.execute(query, tuple(data_parts))
conn.commit()
# Construct reply message
transaction_number = data_parts[0] # Extract transaction number from the data
reply_message = f"F#20=DELETE={transaction_number}<cr><lf>"
logging.info(f"Replying with: {reply_message}")
# Send back confirmation with reply message
reply_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
reply_socket.connect(("10.13.98.xxx", reply_port))
reply_socket.sendall(reply_message.encode())
reply_socket.shutdown(socket.SHUT_WR) # Shutdown the write side of the connection
reply_socket.close() # Close the connection
# Function to receive data
def receive_data():
\# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the address
server_address = ('10.13.98.xxx', 8080)
server_socket.bind(server_address)
# Listen for incoming connections
server_socket.listen(1)
# Connect to the database
conn = create_connection()
logging.info("Listening for connections...")
while True:
# Accept a connection
connection, client_address = server_socket.accept()
try:
# Log connection information
logging.info(f"Connection from: {client_address}")
# Receive data
data = connection.recv(1024).decode()
if data:
# Log received data
logging.info(f"Received data: {data}")
# Insert data into the database and send confirmation
insert_data(conn, data, connection)
except Exception as e:
# Log errors
logging.error(f"Error: {e}")
finally:
# Close the connection
connection.close()
# Call the function to start listening
receive_data()
我尝试使用 telnet ping ip 和端口,一切似乎都很好。
我认为您正在混合服务器和客户端连接。如果您想作为服务器接受连接,则可以在 0.0.0.0 处绑定,例如在服务器套接字上。与外部服务器连接只需要对方的地址 – 一个板球运动员 4 月 18 日 12:53 发表评论