RPi3, Raspian Jessie, Python 2.7. Hello all, I am struggling trying to do an IPC using Unix Domain Sockets. I had it working some months ago, but alas, I can't seem to put my hands on those images with working code. My client is getting "errno 111: Connection refused" when it tries to connect to a socket created by another Python program. I am currently using some demo code I found here, and I believe it to be OK. Here's the code:
Socket Creator:
import socket
import os, os.path
import time
if os.path.exists( "/tmp/python_unix_sockets_example" ):
os.remove( "/tmp/python_unix_sockets_example" )
print "Opening socket..."
server = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM )
server.bind("/tmp/python_unix_sockets_example")
print "Listening..."
while True:
datagram = server.recv( 1024 )
if not datagram:
break
else:
print "-" * 20
print datagram
if "DONE" == datagram:
break
print "-" * 20
print "Shutting down..."
server.close()
os.remove( "/tmp/python_unix_sockets_example" )
print "Done"
Socket Connector:
import socket
import os, os.path
print "Connecting..."
if os.path.exists( "/tmp/python_unix_sockets_example" ):
client = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM )
client.connect( "/tmp/python_unix_sockets_example" )
print "Ready."
print "Ctrl-C to quit."
print "Sending 'DONE' shuts down the server and quits."
while True:
try:
x = raw_input( "> " )
if "" != x:
print "SEND:", x
client.send( x )
if "DONE" == x:
print "Shutting down."
break
except KeyboardInterrupt, k:
print "Shutting down."
client.close()
else:
print "Couldn't Connect!"
print "Done"
ls -l of socket:
srwxr-xr-x 1 root root 0 May 19 14:26 python_unix_sockets_example
I'm thinking this is some stupid, simple thing, but I've been pounding my head against it for a couple days now. Thanks for all help!
20160520@1413EDT update: Still fighting. Changed from Unix Domain Sockets to regular IP sockets (socket.AF_INET), pointed both creator and client to "localhost", ran out of two separate terminal sessions on the same RPi3 and the client finally connects. Now, let me try to work backwards to local domain sockets and see if a miracle will occur...Stay tuned.
1 Answer 1
Finally: The reason I was unable to connect both ends to the domain socket was because (for an unknown reason to me) I was running my logic out of Idle. If I fired up two different terminal sessions; one with the creator, and the other with the client, all worked as expected. There's three days of my life that I won't get back (unless I forget how I got things going and go back through this again).
Thanks to @ott and @Shan-Desai for your help.
Explore related questions
See similar questions with these tags.
ls -l
output of the socket to your question.bind()
you need to specify theport
and thehost
? for Instanceserver.bind((host, Port))
also I really also think that when using UDP You need to usebind()
at the client end too.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
this makes the multiuse of socket.