I have a small issue.
How can I close UDP-socket on the server-side correctly? Below you can find a part of my code. I guess, you do not need the whole code for my case.
Server Code
import ns_beam # my module
import socket
import pickle
host = socket.gethostname()
port_client = 60000
port_server = 50000
CLIENT_ADDRESS = (host, port_client)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((host, port_server))
while True:
message, address = server_socket.recvfrom(1024)
recv_data = pickle.loads(message) # convert data to pickle
print(f"Received force from PS = {round(recv_data, 3)} [kN]")
result = ns_beam.num_sub_structure(f_sensor=recv_data, num_elem_tot=element_number) # calculation
print(f"Displacement of NS = {round(result, 3)} [mm]")
# code to send data
sent_data = pickle.dumps(result) # convert data to pickle
server_socket.sendto(sent_data, # data to be sent
CLIENT_ADDRESS) # details of destination
server_socket.close()
Client Code
import ps_truss # my module
import socket
import pickle
import time
host = socket.gethostname()
port_client = 60000
port_server = 50000
SERVER_ADDRESS = (host, port_server)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.bind((host, port_client))
# ===============================
# ===============================
# create an array for E_i, where every next E_i is 10% less than previous
E_arr = []
E = 210000 # [N/mm2]
E_0 = 210000 # [N/mm2]
while E > E_0 * 0.3:
E = E - E * 0.1
E_arr.append(E)
# ===============================
# ===============================
# ============ initial step. Start
result_init = ps_truss.ps_sub_structure(v_2=v_2_init, e_mod=E) # calculation
# code to cent data
data_send_init = pickle.dumps(result_init) # convert data to pickle
client_socket.sendto(data_send_init, # data to be sent
SERVER_ADDRESS) # details of destination
# ============ initial step. End
counter = 0
while True:
for E_i in E_arr:
message, address = client_socket.recvfrom(1024)
recv_data = pickle.loads(message)
print(f'received displacement from NS:{round(recv_data, 3)} [mm]')
time.sleep(1)
result = ps_truss.ps_sub_structure(v_2=recv_data, e_mod=E_i) # calculation
print(f'force from PS:{round(result, 3)} [kN]')
# code to cent data
sent_data = pickle.dumps(result) # convert data to pickle
client_socket.sendto(sent_data, # data to be sent
SERVER_ADDRESS) # details of destination
counter += 1
print(counter)
if counter > len(E_arr):
break
break
print("The client socket is closed")
client_socket.close()
On the Server Side the code server_socket.close()
is unreachable. I understand, that first of all the while loop shall be closed.
My idea is as long I receive the data from client, the while loop will not be interrupted. If I do not receive data (e.g. for 30 sec.) the server shall close a socket.
Could you please help me to implement this?
Many thanks in advance!