Created
August 23, 2020 09:41
-
-
Save dasl-/e220fedee43ac16dc212fd053775e4e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import sys | |
import traceback | |
# 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('connecting to {}'.format(server_address)) | |
try: | |
sock.connect(server_address) | |
except Exception as e: | |
print('Exception: {}'.format(traceback.format_exc())) | |
sys.exit(1) | |
try: | |
# Send data | |
message = 'This is the message. It will be repeated.' | |
print('sending "{}"'.format(message)) | |
sock.sendall(message.encode()) | |
amount_received = 0 | |
amount_expected = len(message) | |
while amount_received < amount_expected: | |
data = sock.recv(16) | |
amount_received += len(data) | |
print('received "{}"'.format(data)) | |
finally: | |
print('closing socket') | |
sock.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import sys | |
import os | |
import select | |
server_address = './uds_socket' | |
# Make sure the socket does not already exist | |
try: | |
os.unlink(server_address) | |
except OSError: | |
if os.path.exists(server_address): | |
raise | |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) | |
# Bind the socket to the port | |
print("starting up on {}".format(server_address)) | |
sock.bind(server_address) | |
sock.settimeout(3) | |
# Listen for incoming connections | |
sock.listen(10) | |
while True: | |
# Wait for a connection | |
print('waiting for a connection') | |
connection, client_address = sock.accept() | |
try: | |
print('connection from {}'.format(client_address)) | |
# Receive the data in small chunks and retransmit it | |
while True: | |
data = connection.recv(16) | |
print('received "{}"'.format(data)) | |
if data: | |
print('received len {} data. sending data back to the client'.format(len(data))) | |
connection.sendall(data) | |
else: | |
print('no more data from {}'.format(client_address)) | |
ignore1, ignore2, is_errored = select.select([], [], [connection], 0) | |
print("is errored: {}".format(is_errored)) | |
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