-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_wlm.py
More file actions
87 lines (71 loc) · 2.83 KB
/
server_wlm.py
File metadata and controls
87 lines (71 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import socket
import threading
from wlm import *
# Define the server host and port
# HOST = '127.0.0.1' # Localhost
# HOST = '192.168.0.7' # Localhost
HOST = '161.122.203.21'
PORT = 65000 # Port to listen on (non-privileged ports are > 1023)
wlm = WavelengthMeter(debug=False)
# 최대 클라이언트 수 제한
MAX_CLIENTS = 2
connected_clients = []
client_lock = threading.Lock()
def handle_client(client_socket, address):
global connected_clients
with client_lock:
if len(connected_clients) >= MAX_CLIENTS:
print(f"Rejected connection from {address}: too many clients")
client_socket.sendall(f"Server busy. Only {MAX_CLIENTS} clients allowed.")
client_socket.close()
return
connected_clients.append(address)
print(f"Accepted connection from {address} (current: {len(connected_clients)})")
# print(f"New connection from {address}")
try:
while True:
# Receive data from the client
message = client_socket.recv(1024)
if not message:
# Connection closed by the client
break
print(f"Received from {address}: {message.decode('utf-8')}")
# message_in_int = int(message.decode('utf-8'))
# i = message_in_int
# print("Wavelength at channel %d:\t%.6f nm" % (i, wlm.wavelengths[i]))
channel = int(message.decode('utf-8'))
wavelength = wlm.wavelengths[channel]
print(f"Wavelength at channel {channel}: {wavelength:.6f} nm")
# get wavelength meter value by channel
client_socket.sendall(str(wlm.wavelengths[channel]).encode('utf-8'))
except ConnectionResetError:
print(f"Connection with {address} lost")
except KeyboardInterrupt:
print('Exit by Keyboard Interrupt')
exit()
except Exception as e:
print(f"Error with {address}: {e}")
finally:
with client_lock:
if address in connected_clients:
connected_clients.remove(address)
client_socket.close()
print(f"Connection from {address} closed")
def start_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(MAX_CLIENTS) # Listen for up to 5 connections
print(f"Server started on {HOST}:{PORT}")
try:
while True:
# client_socket = None
client_socket, client_address = server.accept()
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
except KeyboardInterrupt:
print("Server is shutting down...")
finally:
server.close()
print("Server stopped.")
if __name__ == "__main__":
start_server()