yoWeb server

 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
#!/usr/bin/env python
import sys
from threading import *
from socket import *
class yoServer(Thread):
def __init__(self):
Thread.__init__(self)
self.__port = 1223
self.__addr = 'localhost'
self.__peers = []
self.__finish = 0
def run(self):
self.__UDPSock = socket(AF_INET, SOCK_DGRAM)
self.__UDPSock.bind((self.__addr, self.__port))
while not self.__finish:
self.__user_msg, self.__user_addr = self.__UDPSock.recvfrom(1024)
#register user ot fuck
if self.__user_addr not in self.__peers:
if self.__user_msg == '/regme':
self.__peers.append(self.__user_addr)
self.__UDPSock.sendto('success', self.__user_addr)
continue
self.__UDPSock.sendto('please register...', self.__user_addr)
continue
#interrupt message check
if self.__user_msg == 'bye-bye':
self.__peers.pop( self.__peers.index(self.__user_addr) )
self.__UDPSock.sendto('You disconnect...', self.__user_addr)
continue
#send message to all
self.send_all(self.__user_msg)
self.send_all('Server OFF!')
self.__UDPSock.close()
def send_all(self, msg):
for peer in self.__peers:
self.__UDPSock.sendto(msg, peer)
def stop(self):
self.__UDPSock.sendto('nil', (self.__addr, self.__port))
self.__finish=1
def who(self):
return self.__peers
if __name__=="__main__":
Server = yoServer()
Server.start()
input_data=''
while input_data!='exit':
try:
input_data = raw_input('->')
command = input_data.split()
if command[0] == 'who':
peers = Server.who()
for peer in peers:
print peer[0],'--', peer[1]
else:
print "Command not found"
except KeyboardInterrupt:
break
Server.stop()