lang/python/ ClipboardServer
This is one step up from the EchoServer. Usage:
clipsrv # start the server
put key value # stores value in key
putf key filename # stores contents of filename in key
get key # gets what is stored in key
Source
clipsrv:
import socket
HOST = "" # Standard loopback interface address (localhost)
PORT = 4096 # Port to listen on (non-privileged ports are > 1023)
clip = {}
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
try:
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
dat = data.decode()
if "=" in dat:
k,v = dat.split("=",1)
k = k.strip()
v = v.strip()
print(f"put {len(v)} bytes at {k}")
clip[k] = v
dat = f"Stored {len(v)} bytes at {k}"
else:
k = dat.strip()
print(f"get {k}")
if k in clip:
dat = clip[k]
else:
dat = "<no data>"
data = dat.encode()
conn.sendall(data)
except Exception as e:
print(f"Exception {e}")
put
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 4096 # The port used by the server
import sys
args = sys.argv[1:]
try:
k,*vs = args
v = " ".join(vs)
except IndexError:
print(f"put1 key data...")
exit(1)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
x = f"{k}={v}".encode()
s.sendall(x)
data = s.recv(1024)
print(f"Received {data!r}")
putf
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 4096 # The port used by the server
import sys
args = sys.argv[1:]
try:
k,vf,*xs = args
v = open(vf).read()
except Exception as e:
print(e)
print(f"putf key data...")
exit(1)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
x = f"{k}={v}".encode()
s.sendall(x)
data = s.recv(1024)
print(f"Received: {data.decode()}")
get
#!/usr/bin/env python3
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 4096 # The port used by the server
import sys
args = sys.argv[1:]
for arg in args:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(arg.encode())
data = s.recv(1024)
print(f"Received {data.decode()}")