Skip to content

Instantly share code, notes, and snippets.

@reflechant
Created November 3, 2018 20:19
Show Gist options
  • Save reflechant/8609050cd7b398a0154e776760dd2913 to your computer and use it in GitHub Desktop.
Save reflechant/8609050cd7b398a0154e776760dd2913 to your computer and use it in GitHub Desktop.
Simple chat for LAN using UDP (not finished)
import socket
import threading
addr = socket.gethostbyname(socket.gethostname())
port = 22000
srv_addr = (addr, port)
broadcast_addr = ".".join(addr.split('.')[:-1]) + '.255'
nport = 22001
n_srv_addr = (broadcast_addr, port)
peers = {}
def announce(sock):
print("Как тебя зовут? ", end="")
name = input()
while " " in name:
print("Имя должно быть без пробелов")
print("Как тебя зовут? ", end="")
name = input()
sock.sendto(name.encode(), n_srv_addr)
def name_daemon(sock):
def gather():
while True:
data, peer_addr = sock.recvfrom(4096)
name = data.decode()
if name in peers and peers[name] == peer_addr:
print("кто-то пытается выдать себя за", name)
continue
peers[name] = peer_addr
print("В чат зашёл {} с адреса {}:{}".format(
name, peer_addr[0], peer_addr[1]))
return gather
def receiver(sock):
def recv():
while True:
data, peer_addr = sock.recvfrom(4096)
if peer_addr not in peers.values():
name = "аноним"
else:
name = list(peers.keys())[list(
peers.values()).index(peer_addr)]
print("{} > {}".format(name, data.decode()))
return recv
def send(sock):
while True:
try:
msg = input()
except EOFError:
print('\n')
break
if len(msg) == 0:
continue
msg_split = msg.split()
name = msg_split[0]
if name not in peers:
print("Нет такого абонента")
continue
sock.sendto(" ".join(msg_split[1:]).encode(), peers[name])
def main():
sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.bind(srv_addr)
nsock = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
nsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
nsock.bind(n_srv_addr)
name_thread = threading.Thread(target=name_daemon(nsock))
name_thread.start()
announce(nsock)
recv_thread = threading.Thread(target=receiver(sock))
recv_thread.start()
send(sock)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment