4
\$\begingroup\$

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(">>")

    if not msg:
       break
    s.send(msg.encode())
    time.sleep(0.1)
\$\endgroup\$
7
  • \$\begingroup\$ Your indentation within the while True loop seem s to be off. The way it is, it will run for ever. \$\endgroup\$
    – Graipher
    Aug 14, 2016 at 17:50
  • \$\begingroup\$ @Graipher A server is usually supposed to run forever. Do you imply the break is not going to have the intended effect? \$\endgroup\$
    – Mast
    Aug 14, 2016 at 18:07
  • \$\begingroup\$ @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. \$\endgroup\$
    – mdfst13
    Aug 14, 2016 at 18:16
  • \$\begingroup\$ Yes, this is a error on my behalf, my terrible copy and pasting :) \$\endgroup\$
    – cheiffeast
    Aug 14, 2016 at 18:18
  • \$\begingroup\$ 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? \$\endgroup\$
    – cheiffeast
    Aug 14, 2016 at 18:27

1 Answer 1

1
\$\begingroup\$

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()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.