When I send the first value from my py server to the Simulink TCP/IP Client Receive block (non-blocking-mode), nothing happens and the data and status outputs both remain 0. When I send the second value, the first value is received. When I send the third, the second is received. And so on. I have no idea why this is happening. Does anyone know how to fix this, or do I need to work around this phenomenon?
[The if-block and data store memory are for handling the non-blocking mode]
Python Server:
import socket
import struct
def start_tcp_server_v3():
# Initialize socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.settimeout(100) # Set timeout to 100 seconds as specified in Simulink
# Bind the socket
host, port = 'localhost', 50000
server_socket.bind((host, port))
while True:
try:
# Listen for incoming connections
server_socket.listen(1)
print("Server is listening...")
# Establish connection
client_socket, client_address = server_socket.accept()
print(f"Connection established with {client_address}")
# Reset the timeout for the client socket
client_socket.settimeout(None)
while True:
try:
# Get user input for the data to send
user_input = input("Please enter a double value to send: ")
try:
double_value = float(user_input)
except ValueError:
print("Invalid input. Please enter a valid double value.")
continue
# Prepare data
data = struct.pack('>d', double_value) # Big-endian byte order, type double
# Send data
client_socket.sendall(data)
print("Just sent: [ "+str(double_value)+" ]")
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
print("Client disconnected. Returning to listening mode.")
client_socket.close() # Close the client socket
break # Break the inner loop to go back to listening for new connections
except socket.timeout:
print("Server timeout. No client connected.")
continue
except KeyboardInterrupt:
print("Server is shutting down.")
break
finally:
# Close client socket if it exists
if 'client_socket' in locals():
client_socket.close()
# Close the server socket
server_socket.close()
print("Server has been closed.")
# -----------------------------------------
start_tcp_server_v3()