Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Sever.py:
- from socket import *
- import threading
- Server = socket(AF_INET, SOCK_STREAM)
- Server.bind(('127.0.0.1', 12000))
- Server.listen()
- connections = {}
- def SendAllConnections(response, con):
- for connection in connections:
- if not con == connection:
- try: ## sends message
- connection.send(response.encode())
- except: ## removes connection if error
- connection.remove(connection)
- connection.close()
- def ConnectionHandle(con, addr):
- while True:
- try:
- response = con.recv(1024)
- if response:
- response = "["+connections[con]+"] > " + response.decode()
- print("Sending: " + response + " To All Clients")
- SendAllConnections(response, con)
- except:
- con.close()
- SendAllConnections(connections[con] + " Has left the chat", con)
- del connections[con]
- print("Connection Left")
- break
- while True:
- con, addr = Server.accept()
- response = con.recv(1024)
- name = response.decode()
- connections[con] = name # add name
- print(name + " Connected...")
- SendAllConnections(name+" Joined the chat! ", con)
- t = threading.Thread(target= ConnectionHandle, args=(con,addr, ))
- t.start()
- #Clinet.py:
- from socket import *
- import threading
- ClientName = input("Enter your name: ")
- serverName = '127.0.0.1'
- serverPort = 12000
- clientSocket = socket(AF_INET, SOCK_STREAM)
- clientSocket.connect((serverName, serverPort))
- def SendHandle():
- while True:
- try:
- sentence = input("")
- clientSocket.send(sentence.encode())
- except:
- clientSocket.close()
- break
- def RecieveHandle():
- print("You joined the chat room!")
- while True:
- try:
- message = clientSocket.recv(1024).decode()
- print(message)
- except:
- clientSocket.close()
- break
- clientSocket.send(ClientName.encode())
- rht = threading.Thread(target=RecieveHandle)
- rht.start()
- sht = threading.Thread(target=SendHandle)
- sht.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement