-
Notifications
You must be signed in to change notification settings - Fork 17
/
sockets_server.py
61 lines (50 loc) · 1.46 KB
/
sockets_server.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
import socket
import sys
import threading
from Queue import Queue
messages = Queue()
class BroadCastThread(threading.Thread):
def run(self):
global messages
while True:
message, conn_addr = messages.get()
for thread in threading.enumerate():
if isinstance(thread, ChatThread):
if not conn_addr==thread.conn_addr:
thread.conn.sendall(message)
class ChatThread(threading.Thread):
def __init__(self, conn, addr):
super(ChatThread, self).__init__()
self.conn = conn
self.addr = addr
print 'Connected with ' + addr[0] + ':' + str(addr[1])
self.conn_addr = addr[0] + ':' + str(addr[1])
def run(self):
while True:
global messages
data = self.conn.recv(1024)
if data=="\r\n":
break
messages.put((data, self.conn_addr))
self.conn.close()
print "Conection closed with " + self.addr[0] + ":" + str(self.addr[1])
HOST = ''
PORT = 8888
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print "Can't create socket"
sys.exit()
print "socket created"
try:
sock.bind((HOST, PORT))
except socket.error:
print "Cant bind"
sys.exit()
print 'Socket bind complete'
sock.listen(10)
print 'Socket now listening'
BroadCastThread().start()
while True:
conn, addr = sock.accept()
ChatThread(conn, addr).start()