Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.24 KB | None | 0 0
  1. #VERSION 0.2.2
  2. import socket
  3. import threading
  4. import time
  5. import random
  6. import sys
  7. import md5
  8.  
  9. HOSTIP = "130.111.39.241"
  10. HOSTPORT = 25565
  11. SPAMTIMER = .85
  12. SPAMLENGTH = 81
  13. MD5PASS = "8226a96f304d1c92f5d1a8cb7f0fcbdc"
  14.  
  15. class Queue:
  16.     def __init__(self, items):
  17.         self.items = items
  18.         self.modifying = False
  19.    
  20.     def pop(self):
  21.         while self.modifying:
  22.             time.sleep(random.randint(1,5)*.1)
  23.         self.modifying = True
  24.         #Will raise IndexError if queue is empty
  25.         myitem = self.items[0]
  26.         self.items.remove(myitem)
  27.         self.modifying = False
  28.         return myitem
  29.  
  30.     def push(self, item):
  31.         while self.modifying:
  32.             time.sleep(random.randint(1,5)*.1)
  33.         self.modifying = True
  34.         self.items.append(item)
  35.         self.modifying = False
  36.    
  37.     def isEmpty(self):
  38.         if len(self.items) > 0:
  39.             return False
  40.         return True
  41.        
  42. class Server:
  43.     def __init__(self):
  44.         self.toRemove = []
  45.         self.connections = []
  46.         self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  47.         self.removing = False
  48.         self.q = Queue([])
  49.         self.online = True
  50.        
  51.     def start(self):
  52.         print "Starting chat server on "+HOSTIP+":"+str(HOSTPORT)
  53.         try:
  54.             threading.Thread(target=self.sendLoop).start()
  55.             self.s.bind((HOSTIP,HOSTPORT))
  56.             self.s.listen(10)
  57.            
  58.             while self.online:
  59.                 (c,addr) = self.s.accept()
  60.                 username = c.recv(1024).strip()
  61.                 if (" " not in username) and username != "" and len(self.findByUsername(username)) == 0 and len(username) <= 15:
  62.                     while self.removing:
  63.                         time.sleep(.1)
  64.                     client = [username,addr,c]
  65.                     self.connections.append(client)
  66.                     threading.Thread(target=self.getMessage,args=(client,)).start()
  67.                     threading.Thread(target=self.serverSend,args=("["+username+":"+addr[0]+"] has joined.",)).start()
  68.                 else:
  69.                     c.close()
  70.                    
  71.         except KeyboardInterrupt:
  72.                 self.online = False
  73.                 sys.exit(0)
  74.                
  75.     def serverSend(self, message):
  76.         self.q.push([["Server","127.0.0.1",""],message])
  77.    
  78.     def getMessage(self, client):
  79.         while self.online:
  80.             before = time.time()
  81.             #quip is a list [fullClientData,actualMessage]
  82.             quip = [client,""]
  83.             quip[1] = client[2].recv(1024)
  84.             after=time.time()
  85.             if quip[1].strip() != "":
  86.                 if after-before > SPAMTIMER and len(self.findByUsername(client[0])) > 0 and len(quip[1]) < SPAMLENGTH:
  87.                     print "got message:"+client[0]+":"+quip[1]
  88.                     self.q.push(quip)
  89.             else:
  90.                 while self.removing:
  91.                     time.sleep(1)
  92.                 self.toRemove.append(client)
  93.                
  94.     def isWhisper(self, message):
  95.         if message.startswith("/msg") or message.startswith("/tell") or message.startswith("/whisper") or message.startswith("/message"):
  96.             return True
  97.    
  98.     def pushMessage(self):
  99.         quip = self.q.pop()
  100.         print "pushing new message!"
  101.        
  102.         if quip[1].startswith("/"):
  103.             if quip[1].startswith("/help"):
  104.                 threading.Thread(target=self.cmdHelp,args=(quip,)).start()
  105.             elif quip[1].startswith("/online"):
  106.                 threading.Thread(target=self.cmdOnline,args=(quip,)).start()
  107.             elif self.isWhisper(quip[1]):
  108.                 threading.Thread(target=self.cmdWhisper,args=(quip,)).start()
  109.             elif quip[1].startswith("/quit"):
  110.                 quip[0][2].close()
  111.                 self.toRemove.append(quip[0])
  112.             elif quip[1].startswith("/kick"):
  113.                 threading.Thread(target=self.cmdKick,args=(quip,)).start()
  114.         else:
  115.             quip[1] = quip[0][0]+": "+quip[1]
  116.             for client in self.connections:
  117.                 threading.Thread(target=self.sendMessage,args=(quip, client)).start()
  118.    
  119.     def sendLoop(self):
  120.         while self.online:
  121.             try:
  122.                 self.pushMessage()
  123.             except IndexError:
  124.                 self.q.modifying = False
  125.             if len(self.toRemove) > 0:
  126.                 while self.removing:
  127.                     time.sleep(.1)
  128.                 self.removeOld()
  129.            
  130.             time.sleep(.05)
  131.                
  132.     def removeOld(self):
  133.         self.removing = True
  134.         for client in self.toRemove:
  135.             try:
  136.                 client[2].close()
  137.                 self.connections.remove(client)
  138.                 threading.Thread(target=self.serverSend,args=("["+client[0]+":"+client[1][0]+"] has disconnected.",)).start()
  139.             except:
  140.                 pass
  141.         self.removing = False
  142.        
  143.     def sendMessage(self, quip, client):
  144.         try:
  145.             fromuser = quip[0][0]
  146.             client[2].send(quip[1])
  147.         except:
  148.             while self.removing:
  149.                 time.sleep(1)
  150.             self.toRemove.append(client)
  151.            
  152.     def findByUsername(self,username):
  153.         c = []
  154.         for client in self.connections:
  155.             if client[0] == username:
  156.                 return client
  157.         return c
  158.            
  159.     def cmdOnline(self, quip):
  160.         fromclient = quip[0]
  161.         users = []
  162.         for client in self.connections:
  163.             users.append(client[0])
  164.        
  165.         quip[1] = "\nOnline:\n    -"+"\n    -".join(users)
  166.         self.sendMessage(quip,quip[0])
  167.        
  168.     def cmdWhisper(self, quip):
  169.         fromclient = quip[0]
  170.         args = quip[1].split(" ")
  171.         if len(args) < 3:
  172.             return
  173.         else:
  174.             toclient = self.findByUsername(args[1])
  175.             if len(toclient) > 0:
  176.                 quip[1] = "[Whisper from "+fromclient[0]+"]: " + " ".join(args[2:])
  177.                 self.sendMessage(quip,toclient)
  178.                
  179.     def cmdKick(self,quip):
  180.         args = quip[1].split(" ")
  181.         if len(args) == 3:
  182.             password = args[1]
  183.             tokick = self.findByUsername(args[2])
  184.             hasher = md5.new()
  185.             hasher.update(password)
  186.             hex = hasher.hexdigest()
  187.             if hex == MD5PASS:
  188.                 self.serverSend("["+args[2]+"] has been kicked.")
  189.                 quip[1] = "/quit"
  190.                 self.sendMessage(quip,tokick)
  191.                 while self.removing:
  192.                     time.sleep(1)
  193.                 self.toRemove.append(tokick)
  194.    
  195.     def cmdHelp(self,quip):
  196.         tosend = quip[0]
  197.         f = open("help.txt","r")
  198.         data = f.readline()
  199.         while data != "":
  200.             quip[1] = data
  201.             self.sendMessage(quip,tosend)
  202.             data = f.readline()
  203.         f.close()
  204.            
  205. serv = Server()
  206. serv.start()
  207.  
  208. #VERSION 0.1.3
  209. import socket
  210. import time
  211. import threading
  212.  
  213. class Client:
  214.     def __init__(self, username, ip, port):
  215.         self.username = username.strip()
  216.         if username == "" or len(username) > 15:
  217.             return
  218.         self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  219.         try:
  220.             self.socket.connect((ip,port))
  221.             self.socket.send(username)
  222.             self.online = True
  223.         except:
  224.             print "couldn't connect to "+ip+":"+str(port)
  225.             self.online = False
  226.            
  227.     def send(self):
  228.         while self.online:
  229.             try:
  230.                 mymsg = raw_input(self.username+": ")
  231.                 if not mymsg.startswith("/quit"):
  232.                     if mymsg.strip() != "":
  233.                         self.socket.send(mymsg)
  234.                 else:
  235.                     self.socket.send(mymsg)
  236.                     self.online = False
  237.                     self.socket.close()
  238.             except:
  239.                 self.online = False
  240.                 self.socket.close()
  241.            
  242.     def recv(self):
  243.         while self.online:
  244.             try:
  245.                 mymsg = self.socket.recv(1024)
  246.                 if mymsg == "/quit":
  247.                     self.socket.close()
  248.                     self.online = False
  249.                 elif not mymsg.startswith(self.username) and not mymsg.strip() == "":
  250.                     print mymsg
  251.             except:
  252.                 self.online = False
  253.                 self.socket.close()
  254.            
  255. username = raw_input("Enter username (max 15 chars): ")
  256. ip = raw_input("Enter ip: ")
  257. port = input("Enter port: ")
  258.  
  259. connection = Client(username,ip,port)
  260. threading.Thread(target=connection.send).start()
  261. threading.Thread(target=connection.recv).start()
  262.  
  263. ####HELP#####
  264. {} Signifies a collection of aliases
  265. [] signifies a placeholder variable, to be replaced with actual info
  266. /help - show this help menu
  267. /online - shows online users
  268. /{msg|tell|whisper|message} [username] [message] - sends a message that only [username] will see
  269. /quit - is supposed to disconnect, but only works if you do Ctrl-C,/quit,enter
  270. /kick [password] [username] - kicks a user, but only if you know the special password!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement