[python] Python socket.error: [Errno 111] Connection refused

I am trying to write a program for file transfer using sockets. The server end of the code is running fine. However, in the client side I get the following error

Traceback (most recent call last):
File "client.py", line 54, in <module>
uploadFiles(directory)
File "client.py", line 36, in uploadFiles
transferFile(fname)
File "client.py", line 13, in transferFile     
cs.connect((HOST, 36258))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

My code is as follows

import os
import socket

def transferFile(fname):
   HOST = '127.0.0.1'
   CPORT = 36258
   MPORT = 36250
   FILE = fname
   cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   cs.connect((HOST, 36258))
   cs.send("SEND " + FILE)
   cs.close()
   ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   ms.connect((HOST, MPORT))
   f = open(FILE, "rb")
   data = f.read()
   f.close()
   ms.send(data)
   ms.close()

def uploadFiles(directory):
   home = os.getenv("HOME")
   folder = str(home + "/" + directory)
   os.chdir(folder)
   dirList = os.listdir(folder)
   print dirList
   for fname in dirList:
       if fname.endswith('.bin'):
           transferFile(fname)

os.chdir(os.getenv("HOME"))
directory = "testdownload"
if not os.path.exists(directory):
   os.makedirs(directory)
 os.chdir(directory)

uploadFiles(directory)

I tried looking for help on Google and other posts on Stack Overflow, none of them helped. Can someone please help me? The line numbers may be different since I pasted only some part of the code

This question is related to python sockets errno

The answer is


The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to sockets

JS file gets a net::ERR_ABORTED 404 (Not Found) mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 TypeError: a bytes-like object is required, not 'str' Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED No connection could be made because the target machine actively refused it 127.0.0.1 Sending a file over TCP sockets in Python socket connect() vs bind() java.net.SocketException: Connection reset by peer: socket write error When serving a file How do I use setsockopt(SO_REUSEADDR)?

Examples related to errno

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv' MySQL: Error dropping database (errno 13; errno 17; errno 39) Python socket.error: [Errno 111] Connection refused How to create a file in Ruby Cannot assign requested address - possible causes? Python [Errno 98] Address already in use How to know what the 'errno' means?