-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_control.py
65 lines (55 loc) · 1.77 KB
/
server_control.py
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
import socket
import threading
def keyboard():
global sock_l, addr_l
msg = ""
while True:
if len(sock_l) > 0:
msg=raw_input('Please input: ')
# empty msg
if not msg:
continue
# try to remove a socket connection
elif msg == "close socket":
print("connected sock: ")
print(addr_l)
index = int(raw_input('Please input remove_index: '))
if index < len(sock_l):
sock_l[index].shutdown(socket.SHUT_WR)
sock_l[index].close()
sock_l.remove(sock_l[index])
addr_l.remove(addr_l[index])
print("successfully remove socket")
elif index == len(sock_l):
sock_l.clear()
print("clear all socket")
else:
print("cancel remove socket")
# boardcast msg
else:
for sock in sock_l:
sock.send(msg.encode())
return
if __name__ == "__main__":
global sock_l, addr_l
sock_l = []
addr_l = []
address='0.0.0.0'
port=12344
buffsize=1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((address,port))
s.listen(5)
print("connecting to clients...")
ii = 0
tk=threading.Thread(target=keyboard,args=())
tk.start()
while True:
ii = ii + 1
# create a new sock for the client
clientsock,clientaddress=s.accept()
print(clientsock)
print("\nconnect to the " + str(ii) + "th client: " + str(clientaddress))
sock_l.append(clientsock)
addr_l.append(clientaddress)
s.close()