-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatroomServer.py
70 lines (60 loc) · 2.05 KB
/
chatroomServer.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
66
67
68
69
70
# -*- coding: utf-8 -*-
import socket
import threading
import select
import sys
#multi-version support
version = sys.version[0]
if version == '2':
import Queue as Queue
elif version == '3':
import queue as Queue
port = 10001
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setblocking(False)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR , 1)
server_address = ('0.0.0.0',port)
server.bind(server_address)
server.listen(5)
#sockets from which we except to read
inputs = [server]
#sockets from which we expect to write
outputs = []
#Outgoing message queues (socket:Queue)
message_queues = {}
#A optional parameter for select is TIMEOUT
timeout = 20000
server_map = {}
def func():
data = None
while True:
#print('System: server now is listening on port ' + str([port]))
readable , writable , exceptional = select.select(inputs, outputs, inputs, timeout)
if not (readable or writable or exceptional) :
print ("Time out ! ")
break
for s in readable :
if s is server:
# A "readable" socket is ready to accept a connection
connection, client_address = s.accept()
print (str(client_address) + ' logged in')
server_map[connection] = client_address
connection.setblocking(0)
inputs.append(connection)
else:
try:
data = s.recv(1024).decode()
except:
print (" closing", server_map[s])
inputs.remove(s)
s.close()
else:
if data :
print (" received " , [data] , "from ",s.getpeername())
for item in inputs:
if item is server:
pass
else:
item.send(data.encode())
if __name__ == '__main__':
func()