Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a socket server listen on local file [closed]

Tags:

python

sockets

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.

like image 340
stutiredboy Avatar asked Feb 20 '12 13:02

stutiredboy


People also ask

How do you close a socket connection in Python?

Calling conn. close() is indeed the correct way to close the connection.

How do you stop a listening socket in python?

In most cases you will open a new thread or process once a connection is accepted. To close the connection, break the while loop.

Can a server initiate a socket connection?

The server creates a socket and binds a name to the socket, then displays the port number. The program calls listen(3SOCKET) to mark the socket as ready to accept connection requests and to initialize a queue for the requests.

How do I stop a socket server?

The close() method of ServerSocket class is used to close this socket. Any thread currently blocked in accept() will throw a SocketException.


1 Answers

# 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.

like image 128
Irfy Avatar answered Oct 26 '22 15:10

Irfy