Skip to content

Instantly share code, notes, and snippets.

@belyaev-pa
Created April 29, 2019 16:20
Show Gist options
  • Save belyaev-pa/ae3c683b33c0237dba11de9917e9023b to your computer and use it in GitHub Desktop.
Save belyaev-pa/ae3c683b33c0237dba11de9917e9023b to your computer and use it in GitHub Desktop.
socket_server
import socket
import sys
import os
import json
import time
server_address = './uds_socket.s'
# 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
while True:
data = connection.recv(4024)
#d = data.decode('utf8').replace("'", '"')
print(data)
x = json.loads(data, encoding='utf8')
print(sys.stderr, 'received "%s"' % x)
if data:
print(sys.stderr, 'sending data back to the client %')
connection.sendall(data)
else:
print(sys.stderr, 'no more data from', client_address)
break
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