1

I wrote a simple Python 3 TCP multithreaded server and telnet to it. All seems to work until I go to close the telnet connection. When I close the telnet connection ^] and then control+d to exit telnet the server repeatedly prints ''.

Is there something trivial I am missing here to prevent this behavior?

import socket 
from threading import Thread 
from socketserver import ThreadingMixIn 
 
# Multithreaded Python server : TCP Server Socket Thread Pool
class ClientThread(Thread): 
 
    def __init__(self,ip,port): 
        Thread.__init__(self) 
        self.ip = ip 
        self.port = port 
        print ("[+] New server socket thread started for " + ip + ":" + str(port)) 
 
    def run(self): 
        while True : 
            data = conn.recv(2048) 
            #data = "Echo data: " + data.decode()
            print ("Server received data: ", data)
            conn.send(data)  # echo 
 
# Multithreaded Python server : TCP Server Socket Program Stub
TCP_IP = '0.0.0.0' 
TCP_PORT = 2004 
BUFFER_SIZE = 1024  # Usually 1024, but we need quick response 
 
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
tcpServer.bind((TCP_IP, TCP_PORT)) 
threads = [] 
 
while True: 
    tcpServer.listen(4) 
    print ("Multithreaded Python server : Waiting for connections from TCP clients...") 
    (conn, (ip,port)) = tcpServer.accept() 
    newthread = ClientThread(ip,port) 
    newthread.start() 
    threads.append(newthread) 
 
for t in threads: 
    t.join() 



Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received data:  b''
Server received da

1 Answer 1

1

Your client thread seems to loop indefinitely. It will happily continue to (attempt to) read from the closed connection. You should add a check that the data received from the read actually contains bytes. If not, the connection is closed.

So, after

data = conn.recv(2048)

add:

if not data: break
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.