16

Just like MySQL server's /tmp/mysql.sock and client write to this file throught socket or any suggestion to share content between independent process (one update, one read) without memcached or NoSQL server, without multithread or multiprocess.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
stutiredboy
  • 347
  • 1
  • 2
  • 12

1 Answers1

31
# Echo server program
import socket,os

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
    os.remove("/tmp/socketname")
except OSError:
    pass
s.bind("/tmp/socketname")
s.listen(1)
conn, addr = s.accept()
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()


# Echo client program
import socket

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/socketname")
s.send(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received ' + repr(data))

Shamelessly copy-pasted from the Python mailing list.

Rufflewind
  • 8,545
  • 2
  • 35
  • 55
Irfy
  • 9,323
  • 1
  • 45
  • 67
  • this does not work under windows – Har Dec 09 '14 at 14:13
  • 6
    @Har yes - it relies on Unix socket files which Windows does not support (boo, Windows) – Wayne Werner Jan 13 '15 at 16:27
  • I get protocol wrong type for socket: > s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) > s.connect('/dev/log') error: [Errno 91] Protocol wrong type for socket – dalore Jun 03 '15 at 16:42
  • Works fine under Cygwin. And when it works under Cygwin, it works even better under Linux/Unix. Are you perhaps trying it out under Windows without Cygwin? If so, try out the answer to http://stackoverflow.com/questions/2952733/using-sys-socket-h-functions-on-windows – Irfy Jun 04 '15 at 17:48
  • 1
    Here's an archive.org link to [the Python mailing list](https://web.archive.org/web/20120208194121/http://mail.python.org/pipermail/python-list/2007-October/1133164.html) as it's no longer available. – GTBebbo Jan 23 '21 at 16:22