Skip to content

Instantly share code, notes, and snippets.

@CleitonDeLima
Last active March 29, 2018 13:54
Show Gist options
  • Save CleitonDeLima/b074370c4cd35b9c23bd61d368509a0d to your computer and use it in GitHub Desktop.
Save CleitonDeLima/b074370c4cd35b9c23bd61d368509a0d to your computer and use it in GitHub Desktop.
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def receive():
while True:
try:
msg = client_socket.recv(BUFFSIZE).decode("utf8")
print(msg)
except OSError:
break
def send(msg):
client_socket.send(bytes(msg, "utf8"))
if msg == "{quit}":
client_socket.close()
exit(0)
HOST = input('Enter host: ')
PORT = input('Enter port: ')
if not PORT:
PORT = 9000
else:
PORT = int(PORT)
BUFFSIZE = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
while True:
message = input()
if message:
send(message)
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_connections():
while True:
client, client_address = SERVER.accept()
print("%s:%s esá conectado." % (client, client_address))
client.send(bytes("Olá! entre com seu nome: ", "utf8"))
print('stop !')
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
def handle_client(client): # Takes client socket as argument.
name = client.recv(BUFFSIZE).decode("utf8")
welcome = 'Bem vindo %s! Para sair do chat você precisa digitar "{quit}".' % name
client.send(bytes(welcome, "utf8"))
msg = "%s entrou no chat!" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFFSIZE)
if msg != bytes("{quit}", "utf8"):
broadcast(msg, name + ": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s saiu do chat." % name, "utf8"))
break
def broadcast(msg, prefix=""):
for sock in clients:
sock.send(bytes(prefix, "utf8") + msg)
clients = {}
addresses = {}
HOST = input('Enter host: ')
PORT = input('Enter port: ')
if not PORT:
PORT = 9000
else:
PORT = int(PORT)
BUFFSIZE = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Esperando por conexão...")
ACCEPT_THREAD = Thread(target=accept_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment