0

I have two files, client.py and server.py:

client.py

from urllib import request
response = request.urlopen('http://localhost:8000/info')
print('The server said:', response.read())

server.py

from http.server import HTTPServer, BaseHTTPRequestHandler

class CustomServer(BaseHTTPRequestHandler):
  def do_GET(self):

    if self.path == '/info':
      result = 'Hello this is a server'
    else:
      result = 'Invalid'

    self.send_response(200)
    self.end_headers()
    self.wfile.write(result.encode())

server = HTTPServer(('localhost', 8000), CustomServer)
server.serve_forever()

Both these files work well independently:

  • If I alter client.py to request http://stackoverflow.com, I see the proper html result.
  • If I run server.py and use my browser to navigate to localhost:8000/info, I see Hello this is a server

My problem is when I run the server, then the client, as-is. The client will receive an error: Connection Refused, with errno 61.

This error only occurs on a particular MacOS machine. When the same code is run on other machines everything works correctly.

What could be causing this problem?

Gershom Maes
  • 7,358
  • 2
  • 35
  • 55
  • Works fine for me on MacOS. Can you confirm both server and the client are running on the same machine? – Selcuk Oct 24 '19 at 00:08
  • Thanks for verifying - yes both on the same machine. A colleague has run the same code on their mac as well, so we may be ghost-hunting :( I can't personally think what would keep this machine from running the code. – Gershom Maes Oct 24 '19 at 00:10
  • Try running the server and then following the instructions here to make sure it's actually listening: https://stackoverflow.com/questions/4421633/who-is-listening-on-a-given-tcp-port-on-mac-os-x Also, try connecting directly to "127.0.0.1:8000" instead of using localhost – Ammar Askar Oct 24 '19 at 00:23
  • I know that the server is listening because I can hit it from my browser - just not from `urllib`. Unfortunately the problem occurs for both `localhost` and `127.0.0.1` – Gershom Maes Oct 24 '19 at 00:25
  • Can you reach it if you use `nc localhost 8000` in the terminal? – Ammar Askar Oct 24 '19 at 00:32

0 Answers0