-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathsockets_chat_server.py
More file actions
74 lines (63 loc) · 1.81 KB
/
sockets_chat_server.py
File metadata and controls
74 lines (63 loc) · 1.81 KB
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
71
72
73
74
import socket
import sys
import threading
messages = []
condition = threading.Condition()
names = ['Akshar', 'Chhote']
class BroadCastThread(threading.Thread):
def run(self):
global messages
while True:
condition.acquire()
if not messages:
condition.wait()
message, conn_addr = messages.pop(0)
condition.release()
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])
name = names.pop(0)
self.name = name
def run(self):
while True:
global messages
data = self.conn.recv(1024)
#if data=="\r\n":
#break
condition.acquire()
data = self.name + " says " + data
messages.append((data, self.conn_addr))
condition.notify()
condition.release()
self.conn.close()
print "Conection closed with " + self.addr[0] + ":" + str(self.addr[1])
HOST = ''
PORT = 8888
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print "Can't create socket"
sys.exit()
print "socket created"
try:
s.bind((HOST, PORT))
except socket.error:
print "Cant bind"
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
BroadCastThread().start()
while 1:
conn, addr = s.accept()
t = ChatThread(conn, addr)
t.start()
s.close()