Advertisement
Guest User

Untitled

a guest
May 26th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. import threading, socket, time, winsound
  2.  
  3. print(" Welcome To NChatX ! A Simple Chat Application!\n")
  4. port = 5080
  5. connection = []
  6.  
  7. username = str(input("Give Your Username >> "))
  8. print("")
  9.  
  10. def listener():
  11. time.sleep(1)
  12. global username2
  13. while True:
  14. try:
  15. for con in connection:
  16. message = con.recv(1024)
  17. message = message.decode()
  18. print(">> {}: {}".format(username2,message))
  19. winsound.Beep(347,200)
  20. except:
  21. for con in connection:
  22. con.close()
  23. print("{} has left the chat!".format(username2))
  24. time.sleep(3)
  25. exit()
  26. def input_talk():
  27. time.sleep(1)
  28. global username2
  29. while True:
  30. try:
  31. ur_message = str(input("\n"))
  32. ur_message = ur_message.encode()
  33. for con in connection:
  34. con.send(ur_message)
  35. winsound.Beep(1000,200)
  36. except:
  37. pass
  38. def server():
  39. global username2
  40. print("\nBuilding Server For You...")
  41. sock = socket.socket()
  42. cp = socket.gethostname()
  43. sock.bind((cp,port))
  44. time.sleep(2)
  45. print("Built Server! Connection Key: {}".format(cp))
  46. print("\nWaiting For A Connection...\n")
  47. sock.listen(1)
  48. conn, addr = sock.accept()
  49. username_user = username.encode()
  50. conn.send(username_user)
  51. username2 = conn.recv(1024)
  52. username2 = username2.decode()
  53. connection.append(conn)
  54. print("{} has connected to the chat!\n------------------------------------------------------------------------\n".format(username2))
  55. t1 = threading.Thread(target = input_talk)
  56. t2 = threading.Thread(target = listener)
  57. t1.start()
  58. t2.start()
  59.  
  60. def client():
  61. global username2
  62. s = socket.socket()
  63. username_user = username.encode()
  64. server_host = str(input("\nConnection Key: "))
  65. try:
  66. s.connect((server_host,port))
  67. username2 = s.recv(1024)
  68. s.send(username_user)
  69. username2 = username2.decode()
  70. connection.append(s)
  71. print("\nYou have connected to {}'s chat!\n------------------------------------------------------------------------\n".format(username2))
  72. t1 = threading.Thread(target = input_talk)
  73. t2 = threading.Thread(target = listener)
  74. t1.start()
  75. t2.start()
  76. except:
  77. print("\nConnection Key Failure\n")
  78.  
  79. while True:
  80. opt = str(input(">> What Do You Want To Host As?[Client/Server]: "))
  81. if opt.lower() == "client":
  82. client()
  83. break
  84. elif opt.lower() == "server":
  85. server()
  86. break
  87. else:
  88. print("\tERROR "+options+" Is Not An Option\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement