Attachment 'chatserver.py'
Download 1 #!/usr/bin/env python
2 import threading
3 import socket
4 import sys
5 import os
6 import signal
7
8 class ClientThread(threading.Thread):
9
10 def __init__(self,cl_socket,group):
11 threading.Thread.__init__(self)
12 self.cl_socket=cl_socket
13 self.f=self.cl_socket.makefile()
14 self.group=group
15 self.tell_lock=threading.Lock()
16
17 def run(self):
18 while True:
19 self.f.write('Name:')
20 self.f.flush()
21 self.name=self.f.readline().strip()
22 if self.name:
23 break
24 self.group.add(self)
25 for line in self.f:
26 self.group.tell_others(self,line)
27 self.group.remove(self)
28 self.f.close()
29 # self.cl_socket.shutdown(socket.SHUT_RDWR)
30 self.cl_socket.close()
31
32
33 def tell(self,what):
34 self.tell_lock.acquire()
35 self.f.write(what)
36 self.f.flush()
37 self.tell_lock.release()
38
39 class ClientGroup(object):
40
41 def __init__(self):
42 self.clients=[]
43 self.clients_lock=threading.Lock()
44
45 def add(self,client):
46 self.clients_lock.acquire()
47 self.clients.append(client)
48 self.clients_lock.release()
49 self.tell_others(client,'* entered the room *\n')
50
51
52 def remove(self,client):
53 self.clients_lock.acquire()
54 self.clients.remove(client)
55 self.clients_lock.release()
56 self.tell_others(client,'* left the room *\n')
57
58 def tell_others(self,client,line):
59 what=client.name+"> "+line
60 for other in self.clients:
61 other.tell(what)
62
63 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
64 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
65 # Naviazeme ho na port 2222 pre vsetky lokalne adresy
66 s.bind(('',2222))
67 # Najviac 5 spojeni bude cakat vo fronte
68 s.listen(5)
69
70 # Toto je kvoli tomu, aby nam nezostavali zombie
71 # procesy a neprerusoval nas signal SIGCHLD
72 signal.signal(signal.SIGCHLD,signal.SIG_IGN)
73
74 group=ClientGroup()
75 try:
76 while True:
77 connected_socket,address=s.accept()
78 print 'Connected by',address
79 client=ClientThread(connected_socket,group)
80 client.setDaemon(True)
81 client.start()
82 del client
83 except KeyboardInterrupt:
84 pass
85 s.shutdown(socket.SHUT_RDWR)
86 s.close()
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.