Created
November 19, 2012 15:36
-
-
Save quiver/4111310 to your computer and use it in GitHub Desktop.
[python]chat server using multicast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# chat server using multicast | |
# python fork of the original ruby implementation | |
# http://tx.pignata.com/2012/11/multicast-in-ruby-building-a-peer-to-peer-chat-system.html | |
# receiver.py | |
# usage : $ python receiver.py # wait for messages to come in | |
import socket | |
import struct | |
multicast_addr = '224.0.0.1' | |
bind_addr = '0.0.0.0' | |
port = 3000 | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
membership = socket.inet_aton(multicast_addr) + socket.inet_aton(bind_addr) | |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership) | |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
sock.bind((bind_addr, port)) | |
while True: | |
message, address = sock.recvfrom(255) | |
print message |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# chat server using multicast | |
# python fork of the original ruby implementation | |
# http://tx.pignata.com/2012/11/multicast-in-ruby-building-a-peer-to-peer-chat-system.html | |
# send.py | |
# usage : $ python send.py message | |
import socket | |
import struct | |
import sys | |
message = sys.argv[1] if len(sys.argv) > 1 else 'message via multicast' | |
multicast_addr = '224.0.0.1' | |
port = 3000 | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
ttl = struct.pack('b', 1) | |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) | |
sock.sendto(sys.argv[1], (multicast_addr, port)) | |
sock.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 19 should be:
sock.sendto(message.encode(), (multicast_addr, port))
Nice implementation, thanks !