Abdullahafzalkhan

python chat app - server

Apr 26th, 2021 (edited)
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. import socket
  2. import threading
  3. from tkinter import *
  4. from tkinter import scrolledtext
  5. root = Tk()
  6. root.geometry("650x390")
  7. output = scrolledtext.ScrolledText(root, wrap = WORD, bg='black', fg="lime", font = (13))
  8. output.pack()
  9.  
  10. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  11. firstTime = True
  12. PORT = 8080
  13. SERVER = '192.168.1.6'
  14. print(SERVER)
  15. ADDR = (SERVER, PORT)
  16. FORMAT = 'utf-8'
  17. CLIENTS = set()
  18. CLIENTSA = 0
  19.  
  20. server.bind(ADDR)
  21.  
  22. def handle_client(conn, addr):
  23.     global CLIENTS
  24.     global CLIENTSA
  25.     global firstTime
  26.     output.insert(INSERT, "\n ACTIVE CLIENTS: %s" %CLIENTSA)
  27.     output.insert(INSERT,f'\n[NEW CONNECTION] {addr} connected')
  28.     connected = True
  29.     while connected:
  30.         try:
  31.             msg = conn.recv(1024)
  32.             output.insert(INSERT," \n[CLIENT] " + msg.decode(FORMAT))
  33.             print("got msg: " + msg.decode())
  34.             for client in CLIENTS:
  35.                 print(msg.decode(FORMAT).split(","))
  36.                 if "FirstTime" in msg.decode(FORMAT).split(','):
  37.                     message = msg.decode(FORMAT).split(',')[1] + " Joined the Cave"
  38.                     client.send(message.encode(FORMAT))
  39.                     output.insert(INSERT, f"\n{message}")
  40.                 else:
  41.                     client.send(msg)
  42.                     output.insert(INSERT, "\nmessage send")
  43.         except:
  44.             conn.close()
  45.             output.insert(INSERT, "\nCLIENT LEFT")
  46.             CLIENTSA -= 1
  47.             break
  48.  
  49. def start():
  50.     global CLIENTSA
  51.     output.insert(INSERT,'SERVER STARTED')
  52.     server.listen()
  53.     while True:
  54.         conn, addr = server.accept()
  55.         thread = threading.Thread(target=handle_client,args=(conn,addr), daemon=True)
  56.         CLIENTS.add(conn)
  57.         CLIENTSA += 1
  58.         thread.start()
  59.  
  60. startThread = threading.Thread(target=start, daemon=True)
  61. startThread.start()
  62. root.mainloop()
  63.  
  64.  
Add Comment
Please, Sign In to add comment