python3 unixsockets
This commit is contained in:
parent
ffd578ad39
commit
2c0c22538d
22
snipplets/code/Python/unixsockets/client.py
Normal file
22
snipplets/code/Python/unixsockets/client.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
import socket
|
||||||
|
import os
|
||||||
|
|
||||||
|
# Set the path for the Unix socket
|
||||||
|
socket_path = '/tmp/myapp.sock'
|
||||||
|
|
||||||
|
# Create the Unix socket client
|
||||||
|
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
|
||||||
|
# Connect to the server
|
||||||
|
client.connect(socket_path)
|
||||||
|
|
||||||
|
# Send a message to the server
|
||||||
|
message = 'Hello from the client!'
|
||||||
|
client.sendall(message.encode())
|
||||||
|
|
||||||
|
# Receive a response from the server
|
||||||
|
response = client.recv(1024)
|
||||||
|
print(f'Received response: {response.decode()}')
|
||||||
|
|
||||||
|
# Close the connection
|
||||||
|
client.close()
|
49
snipplets/code/Python/unixsockets/server.py
Normal file
49
snipplets/code/Python/unixsockets/server.py
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
import base64
|
||||||
|
|
||||||
|
def prep():
|
||||||
|
srv_sock = '/tmp/myapp.sock'
|
||||||
|
try:
|
||||||
|
os.unlink(srv_sock)
|
||||||
|
except:
|
||||||
|
if os.path.exists(srv_sock):
|
||||||
|
raise
|
||||||
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
try:
|
||||||
|
print('Setting up server socket on %s\n' % srv_sock)
|
||||||
|
sock.bind(srv_sock)
|
||||||
|
sock.listen(1)
|
||||||
|
print('Success, listening on unix domain socket %s\n' % srv_sock)
|
||||||
|
return(sock)
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sock = prep()
|
||||||
|
if not sock:
|
||||||
|
return False
|
||||||
|
while True:
|
||||||
|
connection, client_address = sock.accept()
|
||||||
|
try:
|
||||||
|
buffer = ''
|
||||||
|
rcvd_bytes = 0
|
||||||
|
while True:
|
||||||
|
data = connection.recv(1024)
|
||||||
|
rcvd_bytes = rcvd_bytes + len(data)
|
||||||
|
if not data:
|
||||||
|
print('Finished receiving data\n')
|
||||||
|
break
|
||||||
|
buffer = buffer + data.decode()
|
||||||
|
buffer = buffer[:-1]
|
||||||
|
# print(base64.b64encode(buffer.rstrip('\x00')))
|
||||||
|
print('Total bytes received bytes: %s\n' % len(buffer))
|
||||||
|
finally:
|
||||||
|
print('Closing the connection\n')
|
||||||
|
connection.close()
|
||||||
|
print('Connection closed\n')
|
||||||
|
|
||||||
|
if __name__=="__main__":
|
||||||
|
main()
|
Loading…
Reference in New Issue
Block a user