Reputation: 5231
I'd like to implement the example from python official documentation on socket module using AF_UNIX
socket instead of AF_INET
. So here's how server code looks now:
import socket
import os
filename = '/tmp/mysock'
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
if os.path.exists(filename):
os.remove(filename)
sock.bind(filename)
while 1:
data = sock.recv(1024)
print 'Received', repr(data)
if not data:
break
sock.sendall(data)
sock.close()
When I run it, I get this:
Traceback (most recent call last):
File "/home/somecode/server.py", line 10, in <module>
data = sock.recv(2048)
socket.error: [Errno 22] Invalid argument
Upvotes: 1
Views: 2233
Reputation: 1380
SOCK_STREAM is a stateful socket type, so any connection must first be acknowledged by a listening socket and then new dynamic socket (connection) is used for sending and receiving instead. You can't just receive from listening socket.
Basically you forgot to call sock.listen()
on socket after binding and connection, address = sock.accept()
, which blocks until a connection is established and then returns tuple with new socket (connection) and client address. Then simply use connection.recv()
. This is universal for UNIX sockets and TCP/IP sockets.
For example have a look here.
Upvotes: 4