# 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
import pickle,time,datetime,os

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

def handle(self):
self.temp = []

while True:
msg = self.request.recv(8192)
msg = "[{} {}]: {}".format(datetime.datetime.now().strftime("%H:%M:%S"),
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.serve_forever()


client.py

import socket,pickle,os
import time
s = socket.socket()
s.connect(('localhost',20000))

while True:

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

time.sleep(0.1)
while True:

msg = input(">>")

if not msg:
break
s.send(msg.encode())
time.sleep(0.1)

• Your indentation within the while True loop seem s to be off. The way it is, it will run for ever. – Graipher Aug 14 '16 at 17:50
• @Graipher A server is usually supposed to run forever. Do you imply the break is not going to have the intended effect? – Mast Aug 14 '16 at 18:07
• @Mast I think he or she was pointing out that the break is not inside the loop with the current indentation. The def send seems wrong too, as it doesn't match def handle. – mdfst13 Aug 14 '16 at 18:16
• Yes, this is a error on my behalf, my terrible copy and pasting :) – cheiffeast Aug 14 '16 at 18:18
• I have read some places that using pickle over TCP can be dangerous, if this is true, what other methods can i use to send a list over TCP? – cheiffeast Aug 14 '16 at 18:27

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.
    self.username = self.request.recv(8192)

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