TCP chat room in Python I have recently started looking into networking with Python. I saw some tutorials about the socket library so I decided to give a "live chat room" idea a go. It works (on Windows, os.system("cls") may be problematic) but was just wanting to see how people could improve upon it

server.py

from socketserver import ThreadingTCPServer, BaseRequestHandler
from threading import Thread
import pickle,time,datetime,os


messages = []
temp = []
os.system("cls")
class Echo(BaseRequestHandler):


    def handle(self):
        self.temp = []
        Thread(target=self.send).start()
        self.username = self.request.recv(8192)
        self.username = self.username.decode()
        print("Got connection from {}:{}".format(self.client_address[0],
                                                 self.client_address[1]))

        while True:
            msg = self.request.recv(8192)
            msg = "[{} {}]: {}".format(datetime.datetime.now().strftime("%H:%M:%S"),
                               self.username,
                               msg.decode())

            messages.append(msg)
            print(msg)



            if not msg:
                break


    def send(self):

        global temp, messages
        while 1:


            if len(self.temp) != len(messages):

                data_string = pickle.dumps(messages)
                self.request.send(data_string)
                self.temp = [item for item in messages]
if __name__ == "__main__":
    serv = ThreadingTCPServer(("",20000), Echo)
    serv.serve_forever()


client.py

import socket,pickle,os
from threading import Thread
import time
s = socket.socket()
s.connect(('localhost',20000))
def receive():

    while True:

        data = s.recv(8192)
        data = pickle.loads(data)
        os.system("cls")
       for item in data:
            print(item)


username = input("Enter your username: ")
Thread(target=receive).start()

s.send(username.encode())
time.sleep(0.1)
while True:

    msg = input("&gt;&gt;")

    if not msg:
       break
    s.send(msg.encode())
    time.sleep(0.1)
So... handle() gets an incoming connection. Great! What's not so great is that it then spawns self.send in a thread that will never die.

More minorly, I'm not sure why you'd do

    self.username = self.request.recv(8192)
    self.username = self.username.decode()


instead of just

    self.username = self.request.recv(8192).decode()