Advertisement
Guest User

Untitled

a guest
Nov 20th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. import socket
  2. import time
  3. from enum import Enum
  4.  
  5. sep = '\r\n'
  6. TCP_IP = '127.0.0.1'
  7. TCP_PORT = 5008
  8. BUFFER_SIZE = 20
  9.  
  10.  
  11. class StreamType(Enum):
  12. OPEN = 1
  13. CLOSE = 2
  14.  
  15.  
  16. def prepareData(data):
  17. return (str(data.value) + sep).encode('ascii')
  18.  
  19.  
  20. def getDataBlocking(sock):
  21. buffer = ''
  22. sock.setblocking(1)
  23. isDataFetched = False
  24. while isDataFetched == False:
  25. buffer += str(sock.recv(BUFFER_SIZE), 'ascii')
  26. if sep in buffer:
  27. isDataFetched = True;
  28. return buffer.replace(sep, '')
  29.  
  30.  
  31. def getDataNonBlocking(sock):
  32. buffer = ''
  33. sock.settimeout(0.0)
  34. isDataFetched = False
  35. while isDataFetched == False:
  36. try:
  37. buffer += str(sock.recv(BUFFER_SIZE), 'ascii')
  38. except Exception as e:
  39. return None
  40. if sep in buffer:
  41. isDataFetched = True;
  42. return buffer.replace(sep, '')
  43.  
  44.  
  45. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  46. s.connect((TCP_IP, TCP_PORT))
  47. s.setblocking(0)
  48. s.send(prepareData(StreamType.OPEN))
  49. count = 0;
  50. while True:
  51. data = getDataBlocking(s)
  52. s.send(prepareData(StreamType.OPEN))
  53. time.sleep(1)
  54. if data != None:
  55. print(data)
  56. count += 1
  57. if count==20:
  58. break
  59. s.send(prepareData(StreamType.CLOSE))
  60. s.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement