|
| 1 | +import socket |
| 2 | +import threading |
| 3 | + |
| 4 | +sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 5 | + |
| 6 | +sock.bind(('localhost', 5550)) |
| 7 | + |
| 8 | +sock.listen(5) |
| 9 | +print('Server', socket.gethostbyname('localhost'), 'listening ...') |
| 10 | + |
| 11 | +mydict = dict() |
| 12 | +mylist = list() |
| 13 | + |
| 14 | + |
| 15 | +# 把whatToSay传给除了exceptNum的所有人 |
| 16 | +def tellOthers(exceptNum, whatToSay): |
| 17 | + for c in mylist: |
| 18 | + if c.fileno() != exceptNum: |
| 19 | + try: |
| 20 | + c.send(whatToSay.encode()) |
| 21 | + except: |
| 22 | + pass |
| 23 | + |
| 24 | + |
| 25 | +def subThreadIn(myconnection, connNumber): |
| 26 | + nickname = myconnection.recv(1024).decode() |
| 27 | + mydict[myconnection.fileno()] = nickname |
| 28 | + mylist.append(myconnection) |
| 29 | + print('connection', connNumber, ' has nickname :', nickname) |
| 30 | + tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 进入聊天室】') |
| 31 | + while True: |
| 32 | + try: |
| 33 | + recvedMsg = myconnection.recv(1024).decode() |
| 34 | + if recvedMsg: |
| 35 | + print(mydict[connNumber], ':', recvedMsg) |
| 36 | + tellOthers(connNumber, mydict[connNumber] + ' :' + recvedMsg) |
| 37 | + |
| 38 | + except (OSError, ConnectionResetError): |
| 39 | + try: |
| 40 | + mylist.remove(myconnection) |
| 41 | + except: |
| 42 | + pass |
| 43 | + print(mydict[connNumber], 'exit, ', len(mylist), ' person left') |
| 44 | + tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 离开聊天室】') |
| 45 | + myconnection.close() |
| 46 | + return |
| 47 | + |
| 48 | + |
| 49 | +while True: |
| 50 | + connection, addr = sock.accept() |
| 51 | + print('Accept a new connection', connection.getsockname(), connection.fileno()) |
| 52 | + try: |
| 53 | + # connection.settimeout(5) |
| 54 | + buf = connection.recv(1024).decode() |
| 55 | + if buf == '1': |
| 56 | + connection.send(b'welcome to server!') |
| 57 | + |
| 58 | + # 为当前连接开辟一个新的线程 |
| 59 | + mythread = threading.Thread(target=subThreadIn, args=(connection, connection.fileno())) |
| 60 | + mythread.setDaemon(True) |
| 61 | + mythread.start() |
| 62 | + |
| 63 | + else: |
| 64 | + connection.send(b'please go out!') |
| 65 | + connection.close() |
| 66 | + except: |
| 67 | + pass |
0 commit comments