Skip to content

Instantly share code, notes, and snippets.

@hackerdem
Created May 13, 2016 15:39
Show Gist options
  • Save hackerdem/5f3585ca5824ba7937f6b7319503c51e to your computer and use it in GitHub Desktop.
Save hackerdem/5f3585ca5824ba7937f6b7319503c51e to your computer and use it in GitHub Desktop.
UDP client server application
import argparse
import socket
from datetime import datetime
maxbyte=65535
def server(port):
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',port))
print('Listining at {}'.format(sock.getsockname()))
while True:
data,address=sock.recvfrom(maxbyte)
text=data.decode('ascii')
print('the client at {} says {}'.format(address,text))
data=text.encode('ascii')
sock.sendto(data,address)
def client(port):
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
text='the time is {}'.format(datetime.now())
data=text.encode('ascii')
sock.sendto(data,('127.0.0.1',port))
print('Client is assigned to the address {}'.format(sock.getsockname()))
data,address=sock.recvfrom(maxbyte)
text=data.decode('ascii')
print('the server {} replied {}'.format(address,text))
def main():
choices={'client':client,'server':server}
parser=argparse.ArgumentParser(description='udp communication example')
parser.add_argument('role',choices=choices,help='which role to play')
parser.add_argument('-p',metavar='PORT',type=int,default=1060,help='UDP port(default 1060)')
args=parser.parse_args()
function=choices[args.role]
function(args.p)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment