Skip to content

Instantly share code, notes, and snippets.

@Evidlo
Created March 29, 2019 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Evidlo/9fd28f402914c079e3886800b641f761 to your computer and use it in GitHub Desktop.
Save Evidlo/9fd28f402914c079e3886800b641f761 to your computer and use it in GitHub Desktop.
##################### client ###########################
# sends a single one-line command
import socket
import time
import 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 = '/tmp/socket'
print('connecting to %s' % server_address)
try:
sock.connect(server_address)
except socket.error as e:
print(e)
sys.exit(1)
f = sock.makefile('rwb', buffering=0)
try:
# Send data
print('sending command')
# f.write(b'command1\n')
f.write(b'command')
raise Exception
print(f.read())
finally:
print('closing socket')
f.close()
sock.close()
##################################### server ###################################
# responds with a multiline string, then closes connection
import socket
import sys
import os
server_address = '/tmp/socket'
# 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('starting up on %s' % server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print('waiting')
connection, _ = sock.accept()
f = connection.makefile('rwb', buffering=0)
try:
data = f.readline()
print('received "%s"' % data)
if data:
f.write(b'this is the\nresponse to command 1')
f.close()
else:
print('no more data from', client_address)
except BrokenPipeError:
print('client disconnected')
connection.close()
finally:
# Clean up the connection
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment