Skip to content Skip to sidebar Skip to footer

Read And Write From Unix Socket Connection With Python

I'm experimenting with Unix sockets using Python. I want to create a server that creates and binds to a socket, awaits for commands and sends a response. The client would connect t

Solution 1:

SOCK_DGRAM sockets don't listen, they just bind. Change the socket type to SOCK_STREAM and your listen() will work.

Check out PyMOTW Unix Domain Sockets (SOCK_STREAM) vs. PyMOTW User Datagram Client and Server (SOCK_DGRAM)

Solution 2:

#!/usr/bin/python

import socket
import os, os.path
import timefrom collections import deque

if os.path.exists("/tmp/socket_test.s"):
  os.remove("/tmp/socket_test.s")

server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind("/tmp/socket_test.s")
while True:
  server.listen(1)
  conn, addr = server.accept()
  datagram = conn.recv(1024)
  if datagram:
    tokens = datagram.strip().split()
    if tokens[0].lower() == "post":
      flist.append(tokens[1])
      conn.send(len(tokens) + "")
    elif tokens[0].lower() == "get":
      conn.send(tokens.popleft())
    else:
      conn.send("-1")
    conn.close()

Fixed you else... and SOCK_DGRAM...

Post a Comment for "Read And Write From Unix Socket Connection With Python"