Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 377751
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T14:43:37+00:00 2026-05-12T14:43:37+00:00

My class contains a socket that connects to a server. Some of the methods

  • 0

My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I’m running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server.

Problem is that the server only handles one connection at a time (by design) and the “old” socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn’t the socket automatically close?

When it is “stuck”, netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn’t handling the new one yet.

I run this against a dummy server that replies “error\n” to every incoming line.

EDIT: see my comment on Mark Rushakoff’s answer below. An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed.

import socket

class MyException(Exception):
    pass

class MyClient(object):

    def __init__(self, port):
        self.sock = socket.create_connection(('localhost', port))
        self.sockfile = self.sock.makefile()

    def do_stuff(self):
        self._send("do_stuff\n")
        response = self._receive()
        if response != "ok\n":
            raise MyException()
        return response

    def _send(self, cmd):
        self.sockfile.write(cmd)
        self.sockfile.flush()

    def _receive(self):
        return self.sockfile.readline()

def connect():
    c = MyClient(9989)
    # On the second iteration, do_stuff() tries to send data and
    # hangs indefinitely.
    print c.do_stuff()

if __name__ == '__main__':
    for _ in xrange(3):
        try:
            connect()
        except MyException, e:
            print 'Caught:', e
            # This would be the workaround if I had access to the
            # MyClient object:
            #c.sock.close()
            #c.sockfile.close()

EDIT: Here’s the (ugly) server code:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.bind(('localhost', 9989))
s.listen(5)
(c,a) = s.accept()
f = c.makefile()
print f.readline()
f.write('error\n')
f.flush()
(c2,a) = s.accept()
f = c.makefile()
print f.readline()
s.close()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T14:43:37+00:00Added an answer on May 12, 2026 at 2:43 pm

    This is an artifact of garbage collection. Even though the object is out of scope, it is not necessarily collected and therefore destroyed until a garbage collection run occurs — this is not like C++ where a destructor is called as soon as an object loses scope.

    You can probably work around this particular issue by changing connect to

    def connect():
        try:
            c = MyClient(9989)
            # On the second iteration, do_stuff() tries to send data and
            # hangs indefinitely.
            print c.do_stuff()
        finally:
            c.sock.close()
            c.sockfile.close()
    

    Alternatively, you could define __enter__ and __exit__ for MyClient, and do a with statement:

    def connect():
        with MyClient(9989) as c:
            print c.do_stuff()
    

    Which is effectively the same as a try-finally.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class that contains two methods like these: public String getFoo(Int32 a)
I have a class that encapsulates tcp socket communications with a server. For each
I have a class that contains some data, and I would like to add
The Database Forge Class contains functions that help you manage your database. It can:
My Java class contains the following methods: public static void main(String[] argv) //start the
I have a class that I need to binary serialize. The class contains one
In .NET, if a class contains a member that is a class object, should
I currently have 2 concrete methods in 2 abstract classes. One class contains the
I have a class that contains a dynamically allocated array, say class A {
I have a class which expects a stream that contains an XML file. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.