Advertisement
here2share

# peer2peer.py

Jan 15th, 2019
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. # peer2peer.py
  2. # Note: The client and server should be run in separate terminal windows, so they can communicate with each other
  3.  
  4. import socket
  5. import sys
  6.  
  7. hosts = 8888, 8080, 7272
  8.  
  9. serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  10. for host in hosts:
  11.     try:
  12.         serversocket.bind(('localhost', host))
  13.         break
  14.     except:
  15.         0
  16. serversocket.listen(5) # become a server socket, maximum 5 connections
  17.  
  18. clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  19. clientsocket.connect(('localhost', host))
  20.  
  21. c, addr = serversocket.accept()
  22. print("Connection Accepted From " + repr(addr[1])) + " -- localhost: " + str(host)
  23.  
  24. try:
  25.     # Send data
  26.     message = 'Hello. This is the message that will be repeated in segments.'
  27.     print >>sys.stderr, 'sending "%s"' % message
  28.     print
  29.     clientsocket.sendall(message)
  30.     while message:
  31.         data = c.recv(16)
  32.         message = message.replace(data,'')
  33.         print >>sys.stderr, 'received "%s"' % data
  34. finally:
  35.     0
  36. 0
  37. print
  38. clientsocket.send('hello world')
  39.  
  40. while 1:
  41.     print "The Following Message Has Been Sent --"
  42.     print ">>> " + c.recv(1026)
  43.     print
  44.     data = str(raw_input('Type Anything And Click Enter: '))
  45.     clientsocket.send(data)
  46. c.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement