Skip to content

Instantly share code, notes, and snippets.

@nuald nuald/chat.py
Last active Jul 2, 2016

Embed
What would you like to do?
Multicasting chat sample
#!/usr/bin/env python3
""" Multicasting chat application """
import socket
import struct
import sys
from threading import Thread
MADDX = '225.100.100.100'
PORT = 6543
def listen_messages(is_listening):
""" Socket listening thread """
print('Start listening...')
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', PORT))
ip_mreq = struct.pack('4sl', socket.inet_aton(MADDX), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, ip_mreq)
sock.settimeout(1)
while is_listening():
try:
print(sock.recv(10240))
sys.stdout.flush()
except socket.timeout:
pass
print('Stop listening...')
def main():
""" The program entry point """
is_listening = False
name = input('Enter your name: ')
listening_thread = Thread(target=listen_messages, args=(lambda: is_listening,))
is_listening = True
listening_thread.start()
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
while is_listening:
try:
line = input()
msg = '%s: %s' % (name, line)
sock.sendto(msg.encode('utf-8'), (MADDX, PORT))
except (EOFError, KeyboardInterrupt):
is_listening = False
listening_thread.join()
except KeyboardInterrupt:
pass
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.