Skip to content

Instantly share code, notes, and snippets.

@zeimusu
Created October 9, 2013 20:18
Show Gist options
  • Save zeimusu/6907638 to your computer and use it in GitHub Desktop.
Save zeimusu/6907638 to your computer and use it in GitHub Desktop.
UDP server and client for the port 17 "Quote of the day" service Sits on UDP 17 and serves a quote in response to any request.
#!/usr/bin/env python3
from socket import *
import sys
s = socket(AF_INET,SOCK_DGRAM)
try:
port = int(sys.argv[2])
except ValueError:
print("Usage: quote [host] [port]
except IndexError:
port = 17
try:
host = sys.argv[1]
except IndexError:
host = "localhost"
msg_bytes = b"get"
s.sendto(msg_bytes, (host,port))
d = s.recvfrom(1024)
reply = d[0].decode()
addr = d[1]
print("The Oracle replies:\n",reply)
Your lucky color has faded.
%
Your lucky number has been disconnected.
%
Your lucky number is 3552664958674928. Watch for it everywhere.
%
Your true value depends entirely on what you are compared with.
%
"Yow! Am I having fun yet?"
-- Zippy the Pinhead
%
YOW!! Everybody out of the GENETIC POOL!"
%
Zero Defects, n.:
The result of shutting down a production line.
%
Zounds! I was never so bethumped with words
since I first called my brother's father dad.
-- William Shakespeare, "King John"
#!/usr/bin/env python3
import socket
import random
quotes =[]
quotefn = "quotes.txt"
quotesep = "%\n"
host = "" # from all
port = 17
def loadquotes(quotefile):
global quotes
currentquote = ""
for line in quotefile:
if line == quotesep and currentquote != "":
quotes.append(currentquote)
currentquote=""
else:
currentquote += line
if currentquote != "":
quotes.append(currentquote)
def quote():
return random.choice(quotes)
def main():
quotefile= open(quotefn,"r")
loadquotes(quotefile)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((host,port))
while True:
data,addr = s.recvfrom(4096)
q = quote()
qbytes = q.encode()
s.sendto(qbytes,addr)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment