server.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import socket
  2. import sys
  3. # save request code, make var for tcp socket port
  4. requestcode = sys.argv[1]
  5. rport = 0
  6. # start udp socket, declare tcp socket var
  7. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  8. tsock = None
  9. # get udp socket port from system, save in a var
  10. sock.bind(('', 0))
  11. nport = sock.getsockname()[1]
  12. print("SERVER_PORT=", nport, sep="")
  13. # make flag to see if we are waiting for a confirmation or a new connection
  14. newConn = True
  15. # listen for msgs
  16. while True:
  17. message, clientAddress = sock.recvfrom(1024)
  18. message = message.decode()
  19. # match, create tcp socket
  20. if (message == requestcode and newConn):
  21. tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  22. tsock.bind(('', 0))
  23. rport = tsock.getsockname()[1]
  24. print("SERVER_TCP_PORT=", rport, sep="")
  25. sock.sendto(str(rport).encode(), clientAddress) # send new socket port to client
  26. newConn = False
  27. # get confirmation of port, send OK
  28. confirm, newaddr = sock.recvfrom(1024)
  29. if (confirm.decode() == str(rport)):
  30. sock.sendto("correct".encode(), newaddr)
  31. else:
  32. print("Received wrong port number, fail")
  33. exit(1)
  34. tsock.listen(1)
  35. # now put logic for TCP socket behaviour
  36. #while True:
  37. tempsock, addr = tsock.accept()
  38. msg = tempsock.recv(1024).decode()
  39. print("SERVER_RCV_MSG='", msg, "'", sep="")
  40. reply = msg[::-1]
  41. tempsock.send(reply.encode())
  42. newConn = True
  43. tempsock.close()
  44. # match, send a confirmation msg
  45. elif (newConn == False and message == rport):
  46. sock.sendto("correct".encode(), clientAddress)
  47. # client screwed up something other than sending the wrong requestcode
  48. elif (newConn != False):
  49. newConn = True
  50. tsock.close()