server.py
import socketimport sys
import os
server_address = './uds_socket'
recv_buf = 1024
# Make sure the socket does not already exist
try:
os.unlink(server_address)
except OSError:
if os.path.exists(server_address):
raise
# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Bind the socket to the port
print >>sys.stderr, 'starting up on %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
data = connection.recv(recv_buf)
print >>sys.stderr, 'received "%s"' % data
finally:
# Clean up the connection
connection.close()
####################################################################
Set timeout for server socket. If server socket doesn't receive any message from
client within 5 secs, record the exception and continue.
####################################################################
sock.settimeout(5.0)
try:
connection, client_address = sock.accept()
except socket.timeout:
print >>sys.stderr, 'sock accept timeout. No message received from client'
continue
####################################################################
client.py
import socketimport sys
# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = './uds_socket'
print >>sys.stderr, 'connecting to %s' % server_address
try:
sock.connect(server_address)
except socket.error, msg:
print >>sys.stderr, msg
sys.exit(1)
try:
# Send data
message = 'Hi Server.. I am client.'
print >>sys.stderr, 'sending "%s"' % message
sock.sendall(message)
finally:
print >>sys.stderr, 'closing socket'
sock.close()