Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. import socket
  2.  
  3. recvbuf = b""
  4.  
  5. def recv_msg_blocking(recvbuf, conn):
  6. while True:
  7. recvbuf += conn.recv(128)
  8. if b"\n" in recvbuf:
  9. (msg, newline, recvbuf) = recvbuf.partition(b"\n")
  10. print("Received message: '{}'".format(msg))
  11. return msg
  12.  
  13. def send_msg(conn, msg):
  14. print( "Sending message: '{}'".format( msg ) )
  15. conn.sendall(msg)
  16.  
  17. port = 4242
  18. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  19. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  20. s.bind(("127.0.0.1", port))
  21. s.listen()
  22. conn, addr = s.accept()
  23. with conn:
  24. print( 'Connected by', addr )
  25. while True:
  26. msg = recv_msg_blocking(recvbuf, conn)
  27. if msg == b"Stop":
  28. print("stopping...")
  29. break
  30. # Person beep
  31. if msg.startswith(b"beep"):
  32. # reply: time step, elevator 5 assigned to the person who beeped
  33. send_msg( conn, b"beep 1 5\n" )
  34. # State update of all elevators
  35. if msg.startswith(b"update"):
  36. # reply:
  37. # time step,
  38. # we have 4 elevators,
  39. # - elevator 1 at floor 1 should go up
  40. # - elevator 2 at floor 1 should open
  41. # - elevator 3 at floor 5 should open
  42. # - elevator 4 at floor 7 should close
  43. send_msg( conn, b"update 1 4 1 up 1 open 5 open 7 close\n" )
  44. else:
  45. print( "Unexpected message", msg )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement