Advertisement
MrLunk

Rpi to Rpi 2-way Client-Server Socket communication (python)

Oct 31st, 2018
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. sudo pt-get install socket
  2.  
  3. TCP communication:
  4. ------ socket server -----
  5.  
  6. import socket
  7.  
  8. HOST = '' # Server IP or Hostname
  9. PORT = 12345 # Pick an open Port (1000+ recommended), must match the client sport
  10. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  11. print 'Socket created'
  12.  
  13. #managing error exception
  14. try:
  15.     s.bind((HOST, PORT))
  16.     except socket.error:
  17.     print 'Bind failed '
  18.  
  19.     s.listen(5)
  20.     print 'Socket awaiting messages'
  21.     (conn, addr) = s.accept()
  22.     print 'Connected'
  23.  
  24. # awaiting for message
  25. while True:
  26.     data = conn.recv(1024)
  27.     print 'I sent a message back in response to: ' + data
  28.     reply = ''
  29.  
  30.     # process your message
  31.     if data == 'Hello':
  32.         reply = 'Hi, back!'
  33.         elif data == 'This is important':
  34.         reply = 'OK, I have done the important thing you have asked me!'
  35.  
  36.     #and so on and on until...
  37.     elif data == 'quit':
  38.         conn.send('Terminating')
  39.         break
  40.     else:
  41.         reply = 'Unknown command'
  42.  
  43.     # Sending reply
  44.     conn.send(reply)
  45.     conn.close() # Close connections
  46.  
  47. ---- socket client ---------
  48.  
  49. import socket
  50.  
  51. HOST = '' # Enter IP or Hostname of your server
  52. PORT = 12345 # Pick an open Port (1000+ recommended), must match the server port
  53. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  54. s.connect((HOST,PORT))
  55.  
  56. #Lets loop awaiting for your input
  57. while True:
  58.     command = raw_input('Enter your command: ')
  59.     s.send(command)
  60.     reply = s.recv(1024)
  61.         if reply == 'Terminate':
  62.             break
  63.         print reply
  64.  
  65. ----------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement