Skip to content

Instantly share code, notes, and snippets.

@ardenn
Last active November 1, 2018 12:08
Show Gist options
  • Save ardenn/698ee1485c03317d12e1eaa7c05c9af9 to your computer and use it in GitHub Desktop.
Save ardenn/698ee1485c03317d12e1eaa7c05c9af9 to your computer and use it in GitHub Desktop.
Implement a program to receive incoming socket messages over UDS and send them back to the sender
import socket
import os
# Create a TCP/IP socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server_address = './socket_file'
# Make sure file doesn't exist already
try:
os.unlink(server_address)
except FileNotFoundError:
pass
# Bind the socket to the port
print('Starting up on {}'.format(server_address))
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print('received {!r}'.format(data))
if data:
print('sending data back to the client')
connection.sendall(data)
else:
print('no data from', client_address)
break
finally:
# Clean up the connection
print("Closing current connection")
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment