Guest User

Untitled

a guest
Jan 19th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. import socket
  2.  
  3. host = ''
  4. port = 5560
  5.  
  6. storedMessage = "hello"
  7.  
  8. def setupServer():
  9. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  10. print("Socket created.")
  11. try:
  12. s.bind((host, port))
  13. except socket.error as msg:
  14. print(msg)
  15. print("Socket bind comlete.")
  16. return s
  17.  
  18. def setupConnection():
  19. s.listen(1) # Allows one connection at a time.
  20. conn, address = s.accept()
  21. print("Connected to: " + address[0] + ":" + str(address[1]))
  22. return conn
  23.  
  24. def GET():
  25. reply = storedValue
  26. return reply
  27.  
  28. def REPEAT(dataMessage):
  29. reply = dataMessage[1]
  30. return reply
  31.  
  32. def dataTransfer(conn):
  33. # A big loop that sends/receives data until told not to.
  34. while True:
  35. # Receive the data
  36. data = conn.recv(1024) # receive the data
  37. data = data.decode('utf-8')
  38. # Split the data such that you separate the command
  39. # from the rest of the data.
  40. dataMessage = data.split(' ', 1)
  41. command = dataMessage[0]
  42. if command == 'GET':
  43. reply = GET()
  44. elif command == 'REPEAT':
  45. reply = dataMessage[1]
  46. return reply
  47.  
  48. def dataTransfer(conn):
  49. # A big loop that sends/receives data until told not to.
  50. while True:
  51. # Receive the data
  52. data = conn.recv(1024) # receive the data
  53. data = data.decode('utf-8')
  54. # Split the data such that you separate the command
  55. # from the rest of the data.
  56. dataMessage = data.split(' ', 1)
  57. command = dataMessage[0]
  58. if command == 'GET':
  59. reply = GET()
  60. elif command == 'REPEAT':
  61. reply = REPEAT(dataMessage)
  62. elif command == 'EXIT':
  63. print("Our client has left us :(")
  64. break
  65. elif command == 'KILL':
  66. print("Our server is shutting down.")
  67. s.close()
  68. break
  69. else:
  70. reply = 'Unknown Command'
  71. # Send the reply back to the client
  72. conn.sendall(str.encode(reply))
  73. print("Data has been sent!")
  74. conn.close()
  75.  
  76. s = setupServer()
  77.  
  78. while True:
  79. try:
  80. conn = setupConnection()
  81. dataTransfer(conn)
  82. except:
  83. break
Add Comment
Please, Sign In to add comment