Skip to content

Instantly share code, notes, and snippets.

@miss-invincible
Last active May 17, 2016 04:34
Show Gist options
  • Save miss-invincible/9c249d6c286b966e12cb404e1ba81201 to your computer and use it in GitHub Desktop.
Save miss-invincible/9c249d6c286b966e12cb404e1ba81201 to your computer and use it in GitHub Desktop.
import socket
import sys
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
message = 'message sent from client.'
try:
# Send data
print >>sys.stderr, 'sending "%s"' % message
sent = sock.sendto(message, server_address)
# Receive response
print >>sys.stderr, 'waiting to receive'
data, server = sock.recvfrom(4096) #this is buffer size
print >>sys.stderr, 'received "%s"' % data
finally:
print >>sys.stderr, 'closing socket'
sock.close()
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
data_from_server = 'this is message from server.'
while True:
print >>sys.stderr, '\nwaiting to receive message'
data, address = sock.recvfrom(4096) #this is buffer size
print >>sys.stderr, 'received %s bytes from %s' % (len(data), address)
print >>sys.stderr, data
if data:
sent = sock.sendto(data_from_server, address)
print >>sys.stderr, 'sent %s bytes back to %s' % (sent, address)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment