CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day14/chatserver.py
Views: 729
1
from socket import socket
2
from threading import Thread
3
4
5
def main():
6
7
class ClientHandler(Thread):
8
9
def __init__(self, client):
10
super().__init__()
11
self._client = client
12
13
def run(self):
14
try:
15
while True:
16
try:
17
data = self._client.recv(1024)
18
if data.decode('utf-8') == 'byebye':
19
clients.remove(self._client)
20
self._client.close()
21
break
22
else:
23
for client in clients:
24
client.send(data)
25
except Exception as e:
26
print(e)
27
clients.remove(self._client)
28
break
29
except Exception as e:
30
print(e)
31
32
server = socket()
33
server.bind(('10.7.189.118', 12345))
34
server.listen(512)
35
clients = []
36
while True:
37
curr_client, addr = server.accept()
38
print(addr[0], '连接到服务器.')
39
clients.append(curr_client)
40
ClientHandler(curr_client).start()
41
42
43
if __name__ == '__main__':
44
main()
45
46