Sockets on Python


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # Client program
  2.  
  3. from socket import *
  4.  
  5. # Set the socket parameters
  6. host = "localhost"
  7. port = 21567
  8. buf = 1024
  9. addr = (host,port)
  10.  
  11. # Create socket
  12. UDPSock = socket(AF_INET,SOCK_DGRAM)
  13.  
  14. def_msg = "===Enter message to send to server===";
  15. print "\n",def_msg
  16.  
  17. # Send messages
  18. while (1):
  19. data = raw_input('>> ')
  20. if not data:
  21. break
  22. else:
  23. if(UDPSock.sendto(data,addr)):
  24. print "Sending message '",data,"'....."
  25.  
  26. # Close socket
  27. UDPSock.close()
  28.  
  29.  
  30. ################################################################################
  31.  
  32. # Server program
  33.  
  34. from socket import *
  35.  
  36. # Set the socket parameters
  37. host = "localhost"
  38. port = 21567
  39. buf = 1024
  40. addr = (host,port)
  41.  
  42. # Create socket and bind to address
  43. UDPSock = socket(AF_INET,SOCK_DGRAM)
  44. UDPSock.bind(addr)
  45.  
  46. # Receive messages
  47. while 1:
  48. data,addr = UDPSock.recvfrom(buf)
  49. if not data:
  50. print "Client has exited!"
  51. break
  52. else:
  53. print "\nReceived message '", data,"'"
  54.  
  55. # Close socket
  56. UDPSock.close()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.