Advertisement
IsakViste

Chatroom.py

Apr 10th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.28 KB | None | 0 0
  1. import socket
  2. import select
  3. import threading
  4.  
  5. HOST = ''
  6. PORT = 7777
  7.  
  8. #### 1 ####
  9.  
  10. # Version UDP
  11. def v_UDP():
  12.     with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, 0) as s:
  13.         s.bind((HOST, PORT))
  14.         while True:
  15.             mess, addr = s.recvfrom(1500)
  16.             print("Message:", mess)
  17.             if not mess: break
  18.             s.sendto(mess, addr)
  19.  
  20. # Version TCP -1- Threads
  21. def v_TCP1():
  22.     with socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0) as s:
  23.         s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  24.         s.bind((HOST, PORT))
  25.         s.listen(1)
  26.         while True:
  27.             conn, addr = s.accept()
  28.             threading.Thread(None, f1, None, (conn,)).start()
  29.  
  30. def f1(socket):
  31.     while True:
  32.         data = socket.recv(1024)
  33.         if not data: break
  34.         socket.send(data)
  35.     socket.close()    
  36.  
  37. # Version TCP -2- Select
  38. def v_TCP2():
  39.     l = []
  40.     with socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0) as s:
  41.         s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  42.         s.bind((HOST, PORT))
  43.         s.listen(1)
  44.         while True:
  45.             l1, l2, l3 = select.select(l+[s], [], [])
  46.             for i in l1:
  47.                 if i == s:
  48.                     conn, addr = i.accept()
  49.                     l.append(conn)
  50.                 else:
  51.                     message = f2(l, i)
  52.                     if not message:
  53.                         l.remove(i)
  54.                         i.close()
  55.  
  56. def f2(l, socket):
  57.     data = socket.recv(1024)
  58.     if not data: return False
  59.     for i in l:
  60.         if i != socket:
  61.             i.send(data)
  62.     #print("Message:", data)
  63.     return True
  64.  
  65. #### 2 ####
  66. # Serveur de Chat
  67.  
  68. # Code couleurs pour envoyer des message/infos colorees
  69. # https://stackoverflow.com/questions/287871/
  70. class bcolors:
  71.     HEADER = b'\033[95m'
  72.     OKBLUE = b'\033[94m'
  73.     OKGREEN = b'\033[92m'
  74.     FAIL = b'\033[91m'
  75.     RESET = b'\033[0m'
  76.     BOLD = b'\033[1m'
  77.  
  78. l = {"Public": []}
  79. nicks = {}
  80.  
  81. # Fonction principal de Chatroom
  82. def chatroom():
  83.     with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as s:
  84.         s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  85.         s.bind((HOST, PORT))
  86.         s.listen(1)
  87.         while True:
  88.             l1, l2, l3 = select.select(l["Public"]+[s], [], [])
  89.             for i in l1:
  90.                 if i == s:
  91.                     # client joining
  92.                     conn, addr = i.accept()
  93.                     l["Public"].append(conn)
  94.                     nicks[conn] = str(addr[0])
  95.                     client_connection(conn, addr, True)
  96.                 else:
  97.                     cont = f(i)
  98.                     # client leaving
  99.                     if not cont:
  100.                         l["Public"].remove(i)
  101.                         client_connection(conn, addr, False)
  102.                         i.close()
  103.  
  104. # Reccupere les donnees, et verifie si l'utilisateurs veut utiliser des commandes
  105. # Renvoye False si le client se deconnecte
  106. # Renvoye True sinon
  107. def f(socket):
  108.     data = socket.recv(1024)
  109.  
  110.     # If command is kill return False and kills the client connection to the server
  111.     # If not continue
  112.     cmd = command(data, socket)
  113.     if not cmd:
  114.         return False
  115.     return True
  116.  
  117. # Chat commands that the client has access too
  118. def command(cmd, socket):
  119.     cmds = cmd.decode("utf-8").split(" ")
  120.     #print(cmds)
  121.  
  122.     # KILL command
  123.     if cmds[0] == "KILL" or cmds[0] == "KILL\n" or cmd == b"":
  124.         socket.send(bcolors.HEADER + b"You are now disconnected!"
  125.                     + bcolors.RESET + b"\n\n")
  126.         return False
  127.  
  128.     # JOIN command
  129.     elif cmds[0] == "JOIN" or cmds[0] == "JOIN\n":
  130.         if (len(cmds) < 2):
  131.             socket.send(bcolors.FAIL + b"Channel name not indicated!"
  132.                         + bcolors.RESET + b"\n\n")
  133.         elif l.get(cmds[1][:-1]) == None:
  134.             l[cmds[1][:-1]] = [socket]
  135.             socket.send(bcolors.HEADER + b"Channel "
  136.                         + bcolors.OKBLUE + cmds[1][:-1].encode("utf-8")
  137.                         + bcolors.HEADER + b" has been created!"
  138.                         + bcolors.RESET + b"\n\n")
  139.         elif socket in l[cmds[1][:-1]]:
  140.             socket.send(bcolors.FAIL + b"Can't join a channel you already joined!"
  141.                         + bcolors.RESET + b"\n\n")
  142.         else:
  143.             l[cmds[1][:-1]].append(socket)
  144.             socket.send(bcolors.HEADER + b"You have joined channel "
  145.                         + bcolors.OKBLUE + cmds[1][:-1].encode("utf-8")
  146.                         + bcolors.HEADER + b"!"
  147.                         + bcolors.RESET + b"\n\n")
  148.  
  149.     # PART command
  150.     elif cmds[0] == "PART" or cmds[0] == "PART\n":
  151.         if (len(cmds) < 2):
  152.             socket.send(bcolors.FAIL + b"Channel name not indicated!"
  153.                         + bcolors.RESET + b"\n\n")
  154.         elif l.get(cmds[1][:-1]) == None:
  155.             socket.send(bcolors.FAIL + b"Channel does not exist!"
  156.                         + bcolors.RESET + b"\n\n")
  157.         elif cmds[1][:-1] == "Public":
  158.             socket.send(bcolors.FAIL + b"Can't leave Public channel!"
  159.                         + bcolors.RESET + b"\n\n")
  160.         elif socket not in l[cmds[1][:-1]]:
  161.             socket.send(bcolors.FAIL + b"Can't leave a channel you haven't joined!"
  162.                         + bcolors.RESET + b"\n\n")
  163.         else:
  164.             l[cmds[1][:-1]].remove(socket)
  165.             socket.send(bcolors.HEADER + b"You have left channel "
  166.                         + bcolors.OKBLUE + cmds[1][:-1].encode("utf-8")
  167.                         + bcolors.HEADER + b"!"
  168.                         + bcolors.RESET + b"\n\n")
  169.  
  170.     # LIST command
  171.     elif cmds[0] == "LIST" or cmds[0] == "LIST\n":
  172.         socket.send(bcolors.HEADER + b"List of Users:"
  173.                     + bcolors.RESET + b"\n")
  174.         for i in nicks.values():
  175.             socket.send(b" - "
  176.                         + bcolors.OKGREEN + i.encode("utf-8")
  177.                         + bcolors.RESET + b"\n")
  178.         socket.send(b"\n")
  179.  
  180.     # NICK command
  181.     elif cmds[0] == "NICK" or cmds[0] == "NICK\n":
  182.         if(len(cmds) > 1):
  183.             nicks[socket] = cmds[1][:-1]
  184.             socket.send(bcolors.HEADER + b"You are now known as: "
  185.                         + bcolors.OKGREEN + nicks.get(socket).encode("utf-8")
  186.                         + bcolors.RESET + b"\n\n")
  187.         else:
  188.             socket.send(bcolors.FAIL + b"Nickname not indicated!"
  189.                         + bcolors.RESET + b"\n\n")
  190.  
  191.     # MSG command
  192.     elif cmds[0] == "MSG" or cmds[0] == "MSG\n":
  193.         if (len(cmds) < 3):
  194.             socket.send(bcolors.FAIL + b"Message & Channel not indicated!"
  195.                         + bcolors.RESET + b"\n\n")
  196.         elif l.get(cmds[1]) != None:
  197.             if socket in l[cmds[1]]:
  198.                 msg = ' '.join(cmds[2:])
  199.                
  200.                 for i in l[cmds[1]]:
  201.                     if cmds[1] != "Public":
  202.                         i.send(bcolors.OKBLUE + b"[" + cmds[1].encode("utf-8") + b"] "
  203.                                + bcolors.RESET)
  204.                        
  205.                     if i == socket:
  206.                         i.send(bcolors.OKGREEN + bcolors.BOLD + b"YOU: "
  207.                                + bcolors.RESET + msg.encode("utf-8"))
  208.                     else:
  209.                         i.send(bcolors.OKGREEN + nicks.get(socket).encode("utf-8") + b": "
  210.                                + bcolors.RESET + msg.encode("utf-8"))
  211.             else:
  212.                 socket.send(bcolors.FAIL + b"You are not connected to this channel!"
  213.                             + bcolors.RESET + b"\n\n")
  214.         else:
  215.             socket.send(bcolors.FAIL + b"Channel does not exist!"
  216.                         + bcolors.RESET + b"\n\n")
  217.    
  218.     return True
  219.  
  220. # Sends a message depending on whether the client is connecting or disconnecting
  221. def client_connection(client, addr, joining):
  222.     # if joining or leaving server
  223.     if joining:
  224.         server_message(bcolors.HEADER + b"JOIN ")
  225.     else:
  226.         server_message(bcolors.HEADER + b"PART ")
  227.        
  228.     server_message(bcolors.OKBLUE + nicks.get(client).encode("utf-8") + bcolors.RESET + b"\n")      
  229.  
  230. # Send message to all clients connected to the server
  231. def server_message(byte):
  232.     for i in l["Public"]:
  233.         i.send(byte)
  234.        
  235.  
  236. chatroom()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement