socket server

This commit is contained in:
2021-01-08 02:27:33 +01:00
parent f97d140ecb
commit 2818b67cd5
10 changed files with 177 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python
"""
Socket server.
"""
import socket
import threading
HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!DISCONNECT'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
"""Deal with one client."""
print(f"[NEW CONNECTION] {addr} connected.")
while True:
msg_length = conn.recv(HEADER).decode(FORMAT)
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
break
print(f"[{addr}] {msg}")
conn.close()
def start():
"""Start the server."""
server.listen()
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
if __name__ == "__main__":
print("[STARTING] server is starting ...")
start()
+1
View File
@@ -0,0 +1 @@
:q
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env python
import itertools as it; collatz = lambda n:len(list(it.takewhile(lambda n:n>1, (n:=(n//2 if n%2==0 else 3*n+1) for a in it.repeat(1)))))+1
print(collatz(10))
Executable
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python
import sys
import os
import yaml
from rich import print
if not 'commands.yml' in os.listdir():
print(f"File [bold]commands.yml[/bold] not found in \
[bold]{os.getcwd()}[/bold]!")
quit()
if len(sys.argv)==1:
print("[bold]No command[\bold] given as input.")
quit()
with open('commands.yml') as f:
commands = yaml.load(f, Loader=yaml.FullLoader)
command = sys.argv[1]
if not command in commands:
print(f"Command [bold]{command}[\bold] does not exist.")
quit()
code = commands[command]
os.system(code)
Regular → Executable
View File
Executable
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env python
import sys
import time
while True:
print(sys.argv[1])
time.sleep(1)
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env python
import multiprocessing as mp
print("Number of processors: ", mp.cpu_count())
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python
import socket
import threading
HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
HOST = socket.gethostbyname("localhost")
DISCONNECT_MESSAGE = "!DISCONNECT"
ADDR = (HOST, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
send('test')
send(DISCONNECT_MESSAGE)
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python
"""
Socket HOST.
"""
import socket
import threading
HEADER = 64
PORT = 5050
# HOST = socket.gethostbyname(socket.gethostname())
print("before get host by name")
HOST = socket.gethostbyname('localhost')
print(HOST)
ADDR = (HOST, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!DISCONNECT'
HOST = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST.bind(ADDR)
def handle_client(conn, addr):
"""Deal with one client."""
print(f"[NEW CONNECTION] {addr} connected.")
while True:
msg_length = conn.recv(HEADER).decode(FORMAT)
if not msg_length:
continue
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
print(f"[{addr}] {msg}")
if msg == DISCONNECT_MESSAGE:
break
conn.send("Msg received".encode(FORMAT))
conn.close()
print(f"[NEW CONNECTION] {addr} disconnected.")
def start():
"""Start the HOST."""
HOST.listen()
print("[LISTENING] HOST listening on {HOST}")
while True:
conn, addr = HOST.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
if __name__ == "__main__":
print("[STARTING] HOST is starting ...")
start()
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python
from time import sleep
from rich.console import Console
console = Console()
tasks = [f"task {n}" for n in range(1, 11)]
with console.status("[bold green]Working on tasks...") as status:
while tasks:
task = tasks.pop(0)
sleep(1)
console.log(f"{task} complete")