Advertisement
rfmonk

blocks.py

Jan 25th, 2014
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import socket
  5. import struct
  6. import sys
  7.  
  8. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  9.  
  10. HOST = sys.argv.pop() if len(sys.argv) == 3 else '127.0.0.1'
  11. PORT = 1060
  12. format = struct.Struct('!I')
  13. length = 4000
  14.  
  15.  
  16. def recvall(sock, length):
  17.     data = ''
  18.     while len(data) < length:
  19.         more = sock.recv(length - len(data))
  20.         if not more:
  21.             raise EOFError('socket closed %d bytes into a %d-byte message'
  22.                            % (len(data), length))
  23.         data += more
  24.     return data
  25.  
  26.  
  27. def get(sock):
  28.     lendata = recvall(sock, format.size)
  29.     (length,) = format.unpack(lendata)
  30.     return recvall(sock, length)
  31.  
  32.  
  33. def put(sock, message):
  34.     sock.send(format.pack(len(message)) + message)
  35.  
  36. if sys.argv[1:] == ['server']:
  37.     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  38.     s.bind((HOST, PORT))
  39.     s.listen(1)
  40.     print 'Listening at', s.getsockname()
  41.     sc, sockname = s.accept()
  42.     print 'Accepted connection from', sockname
  43.     sc.shutdown(socket.SHUT_WR)
  44.     while True:
  45.         message = get(sc)
  46.         if not message:
  47.             break
  48.         print 'Message says:', repr(message)
  49.     sc.close()
  50.     s.close()
  51.  
  52. elif sys.argv[1:] == ['client']:
  53.     s.connect((HOST, PORT))
  54.     s.shutdown(socket.SHUT_RD)
  55.     put(s, 'Beautiful is better than ugly.')
  56.     put(s, 'Explicit is better than implicit.')
  57.     put(s, 'Simple is better than complex.')
  58.     put(s, '')
  59.     s.close()
  60.  
  61. else:
  62.     print >>sys.stderr, 'usage: blocks.py server|client [host]'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement