Advertisement
MRobbin99

Python ChatRoom (TCP, Client and Server)

Nov 24th, 2020
1,225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. # Sever.py:
  2. from socket import *
  3. import threading
  4.  
  5. Server = socket(AF_INET, SOCK_STREAM)
  6. Server.bind(('127.0.0.1', 12000))
  7. Server.listen()
  8.  
  9. connections = {}
  10. def SendAllConnections(response, con):
  11.     for connection in connections:
  12.         if not con == connection:
  13.             try: ## sends message
  14.                 connection.send(response.encode())
  15.             except: ## removes connection if error
  16.                 connection.remove(connection)
  17.                 connection.close()
  18. def ConnectionHandle(con, addr):
  19.     while True:
  20.         try:
  21.             response = con.recv(1024)
  22.             if response:
  23.                 response = "["+connections[con]+"] > " + response.decode()
  24.                 print("Sending: " + response + " To All Clients")
  25.                 SendAllConnections(response, con)
  26.         except:
  27.             con.close()
  28.             SendAllConnections(connections[con] + " Has left the chat", con)
  29.             del connections[con]
  30.             print("Connection Left")
  31.             break
  32. while True:
  33.     con, addr = Server.accept()
  34.     response = con.recv(1024)
  35.     name = response.decode()
  36.     connections[con] = name # add name
  37.     print(name + " Connected...")
  38.     SendAllConnections(name+" Joined the chat! ", con)
  39.     t = threading.Thread(target= ConnectionHandle, args=(con,addr, ))
  40.     t.start()
  41.  
  42. #Clinet.py:
  43. from socket import *
  44. import threading
  45. ClientName = input("Enter your name: ")
  46. serverName = '127.0.0.1'
  47. serverPort = 12000
  48. clientSocket = socket(AF_INET, SOCK_STREAM)
  49. clientSocket.connect((serverName, serverPort))
  50. def SendHandle():
  51.     while True:
  52.         try:
  53.             sentence = input("")
  54.             clientSocket.send(sentence.encode())
  55.         except:
  56.             clientSocket.close()
  57.             break
  58. def RecieveHandle():
  59.     print("You joined the chat room!")
  60.     while True:
  61.         try:
  62.             message = clientSocket.recv(1024).decode()
  63.             print(message)
  64.         except:
  65.             clientSocket.close()
  66.             break
  67.  
  68. clientSocket.send(ClientName.encode())
  69. rht = threading.Thread(target=RecieveHandle)
  70. rht.start()
  71.  
  72.  
  73. sht = threading.Thread(target=SendHandle)
  74. sht.start()
  75.  
  76.  
  77.  
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement