79

I've been trying to wrap my head around how sockets work, and I've been trying to pick apart some sample code I found at this page for a very simple client socket program. Since this is basic sample code, I assumed it had no errors, but when I try to compile it, I get the following error message.

File "client.py", line 4, in client_socket.connect(('localhost', 5000)) File "", line 1, in connect socket.error: [Errno 111] Connection refused

I've googled pretty much every part of this error, and people who've had similar problems seem to have been helped by changing the port number, using 'connect' instead of 'bind,' and a few other things, but none of them applied to my situation. Any help is greatly appreciated, since I'm very new to network programming and fairly new to python.

By the way, here is the code in case that link doesn't work for whatever reason.

#client example
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 5000))
while 1:
 data = client_socket.recv(512)
 if ( data == 'q' or data == 'Q'):
 client_socket.close()
 break;
 else:
 print "RECIEVED:" , data
 data = raw_input ( "SEND( TYPE q or Q to Quit):" )
 if (data <> 'Q' and data <> 'q'):
 client_socket.send(data)
 else:
 client_socket.send(data)
 client_socket.close()
 break;
jww
104k107 gold badges454 silver badges975 bronze badges
asked Oct 13, 2011 at 4:03
5
  • @TheTromboneWilly Python interpreter would definitely hate it as in SyntaxError :D Commented Jan 5, 2016 at 10:37
  • @JSmyth Not in Python 2 Commented Jan 6, 2016 at 0:36
  • 1
    @TheTromboneWilly good reason to switch to 3 then (; Commented Jan 6, 2016 at 0:37
  • @JSmyth Agreed, along with many other reasons as well! Commented Jan 6, 2016 at 0:39
  • I had the same problem and the issue was that 'localhost' was not properly configured on my Ubuntu machine. I replaced with '' and this fixed the issue. Commented Mar 12, 2019 at 23:50

5 Answers 5

155

Here is the simplest python socket example.

Server side:

import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections
while True:
 connection, address = serversocket.accept()
 buf = connection.recv(64)
 if len(buf) > 0:
 print buf
 break

Client Side:

import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates
Walrus the Cat
2,4447 gold badges39 silver badges66 bronze badges
answered Aug 18, 2013 at 9:23
Sign up to request clarification or add additional context in comments.

4 Comments

How would I do this cross-computer on a LAN connection? I'm having trouble. I emptied "localhost" string from the top example and changed "localhost" to "192.168.1.104" (which is the server's local ip address) but it still didn't work. How does this work?
To answer the commenter above (even if so late)...don't use 'localhost' (if you ping localhost, you will get it resolved to 127.0.0.1) on the server side, but the actual IP of the machine. This assumes that none of these other possible causes blocks the communication: smartftp.com/support/kb/connection-refused-f58.html .
Small issue with this using python3. In the client, you need to change the sending to clientsocket.send(bytes('hello', 'UTF-8')) (or another encoding) due to differences in strings between 2.x and 3.x. (See here)
Shouldn't this socket be closed, rather than just using break?
27

Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import socket
s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import socket
s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
 c, addr = s.accept()
 print("Connection accepted from " + repr(addr[1]))
 c.send("Server approved connection\n")
 print repr(addr[1]) + ": " + c.recv(1026)
 c.close()

Run the server program and then the client one.

Gahan
4,2334 gold badges26 silver badges47 bronze badges
answered Feb 7, 2016 at 15:12

2 Comments

Sorry i made a small mistake in the code for the server program. In line 5 make the port number 1247 not 12.
I have edited your answer to correct the port number. Next time you can do that yourself by using the edit link at the bottom-left of your question.
24

It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. Are you sure you have a server running?

If not, you can use netcat for testing:

nc -l -k -p 5000

Some implementations may require you to omit the -p flag.

answered Oct 13, 2011 at 4:12

2 Comments

That worked! Thank you. I'm so new to network programming. I didn't realize that a server had to be listening for the client to run. It seems like a no-brainer now, but for some reason I was assuming that the client could run by itself. Thanks so much!
@dukbur you need server socket running in order to use client_socket.connect command as it tries to connect it to server. So you get refused error as server is refusing to connect.
4

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

answered Oct 13, 2011 at 4:16

Comments

3

You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type python myprogram.py the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable — and thus you are confusing Python's runtime compilaint that "I can't find anyone listening on port 5000!" with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!

answered Oct 13, 2011 at 4:16

1 Comment

I was aware of how to execute a python program. I just got my terminology confused I guess. The lack of a listener was definitely my problem. Thanks for your answer! :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.