-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver1.py
More file actions
108 lines (84 loc) · 3.48 KB
/
server1.py
File metadata and controls
108 lines (84 loc) · 3.48 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import socket
PORT = 8500
BUFFER_SIZE = 1024
MAX_CONNECTIONS = 10
def main():
# Create server socket
server_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set socket options to reuse address
server_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Set up server address
server_addr = ('0.0.0.0', PORT)
# Bind socket
try:
server_fd.bind(server_addr)
except OSError as e:
print(f"Bind failed: {e}")
server_fd.close()
return
# Listen for connections
try:
server_fd.listen(MAX_CONNECTIONS)
except OSError as e:
print(f"Listen failed: {e}")
server_fd.close()
return
print(f"Server listening on port {PORT}...")
# Lists to store client IPs
client_ips = []
connection_count = 0
try:
while True:
try:
# Accept client connection
client_fd, client_addr = server_fd.accept()
client_ip = client_addr[0]
client_ips.append(client_ip)
connection_count += 1
print(f"Accepted connection {connection_count} from {client_ip}")
# Receive client message
try:
data = client_fd.recv(BUFFER_SIZE)
if data:
message = data.decode('utf-8')
print(f"Client {client_ip} says: {message}")
if len(client_ips)==10:
print(client_ips)
# try:
# hi="hi"
# client_fd.send(hi.encode('utf-8'))
# except:
# print("sending failed")
# try:
# client_ips2="kiran"
# client_fd.send(client_ips2.encode('utf-8'))
# except:
# print("sending failed 2")
# info=client_ips
# try:
# for i in info:
# client_fd.send(str(i).encode('utf-8'))
# except:
# print("sending ips failed")
# Send each IP address individually with newline delimiter
info = client_ips
try:
for i in info:
client_fd.send(f"{i}\n".encode('utf-8'))
# Send sentinel value to indicate end of IPs
# client_fd.send("END\n".encode('utf-8'))
except:
print("sending failed")
except OSError as e:
print(f"Receive or send failed for {client_ip}: {e}")
# finally:
# client_fd.close()
except OSError as e:
print(f"Accept failed: {e}")
continue
except KeyboardInterrupt:
print("\nShutting down server...")
# Close server socket
server_fd.close()
if __name__ == "__main__":
main()