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;
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!Here is the simplest python socket example.
Server side:
Client Side:
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:Some implementations may require you to omit the
-p
flag.It looks like your client is trying to connect to a non-existent server. In a shell window, run:
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.
Here is a pretty simple socket program. This is about as simple as sockets get.
for the client program(CPU 1)
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)
Run the server program and then the client one.