Guest User

Untitled

a guest
Nov 24th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. """Script for Tkinter GUI chat client."""
  3. from socket import AF_INET, socket, SOCK_STREAM
  4. from threading import Thread
  5. import tkinter
  6.  
  7.  
  8. def receive():
  9. """Handles receiving of messages."""
  10. while True:
  11. try:
  12. msg = client_socket.recv(BUFSIZ).decode("utf8")
  13. msg_list.insert(tkinter.END, msg)
  14. except OSError: # Possibly client has left the chat.
  15. break
  16.  
  17.  
  18. def send(event=None): # event is passed by binders.
  19. """Handles sending of messages."""
  20. msg = my_msg.get()
  21. my_msg.set("") # Clears input field.
  22. client_socket.send(bytes(msg, "utf8"))
  23. if msg == "{quit}":
  24. client_socket.close()
  25. top.quit()
  26.  
  27.  
  28. def on_closing(event=None):
  29. """This function is to be called when the window is closed."""
  30. my_msg.set("{quit}")
  31. send()
  32.  
  33. top = tkinter.Tk()
  34. top.title("Chatter")
  35.  
  36. messages_frame = tkinter.Frame(top)
  37. my_msg = tkinter.StringVar() # For the messages to be sent.
  38. my_msg.set("Type your messages here.")
  39. scrollbar = tkinter.Scrollbar(messages_frame) # To navigate through past messages.
  40. # Following will contain the messages.
  41. msg_list = tkinter.Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set)
  42. scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
  43. msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
  44. msg_list.pack()
  45. messages_frame.pack()
  46.  
  47. entry_field = tkinter.Entry(top, textvariable=my_msg)
  48. entry_field.bind("<Return>", send)
  49. entry_field.pack()
  50. send_button = tkinter.Button(top, text="Send", command=send)
  51. send_button.pack()
  52.  
  53. top.protocol("WM_DELETE_WINDOW", on_closing)
  54.  
  55. #----Now comes the sockets part----
  56. HOST = input('Enter host: ')
  57. PORT = input('Enter port: ')
  58. if not PORT:
  59. PORT = 33000
  60. else:
  61. PORT = int(PORT)
  62.  
  63. BUFSIZ = 1024
  64. ADDR = (HOST, PORT)
  65.  
  66. client_socket = socket(AF_INET, SOCK_STREAM)
  67. client_socket.connect(ADDR)
  68.  
  69. receive_thread = Thread(target=receive)
  70. receive_thread.start()
  71. tkinter.mainloop() # Starts GUI execution.
Add Comment
Please, Sign In to add comment