close

How to close a socket connection in python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to close a socket connection in python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to close a socket connection in python?

  1. How to close a socket connection in python?

    If you want the server to keep running (and accept another socket connection) afterwards, you need to put another while True: loop around the code that starts at the s.accept() line

  2. close a socket connection in python

    If you want the server to keep running (and accept another socket connection) afterwards, you need to put another while True: loop around the code that starts at the s.accept() line

Method 1

Calling conn.close() is indeed the correct way to close the connection.

because I tried use conn.close(), then the server seems stop running now:

Right, because that’s what you programmed the server to do. In particular, the client closing the connection causes conn.recv(1024) to return None, which causes your if-test to succeed and then break breaks the server out of its while-loop, and from there the server exits, because there are no further loops for it to execute.

        while True:
            data = conn.recv(1024)
            if not data:
                break

If you want the server to keep running (and accept another socket connection) afterwards, you need to put another while True: loop around the code that starts at the s.accept() line, i.e.:

while True:
   conn, addr = s.accept()
   with conn:
       print('Connected by', addr)
       [...]

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read