From e155420a4b52fb278d8f2ee473cd92a25c4d123e Mon Sep 17 00:00:00 2001 From: Eli Ribble Date: Mon, 19 Jun 2023 16:09:19 -0700 Subject: [PATCH] Working simple client/server --- client.py | 14 ++++++++++++++ datajack/__init__.py | 29 +++++++++++++++++++++++++++++ main.go | 43 +++++++++++++++++++++++++++++++++++++++---- 3 files changed, 82 insertions(+), 4 deletions(-) create mode 100644 client.py create mode 100644 datajack/__init__.py diff --git a/client.py b/client.py new file mode 100644 index 0000000..75bc147 --- /dev/null +++ b/client.py @@ -0,0 +1,14 @@ +import argparse + +import datajack + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("connection_uri", help="The URI to use to connect to the remove datajack.") + args = parser.parse_args() + + with datajack.connection(args.connection_uri) as dj: + dj.send("hi".encode("UTF-8")) + +if __name__ == "__main__": + main() diff --git a/datajack/__init__.py b/datajack/__init__.py new file mode 100644 index 0000000..3cd619b --- /dev/null +++ b/datajack/__init__.py @@ -0,0 +1,29 @@ +import socket +import urllib.parse + +class Connection: + def __init__(self, uri): + parts = urllib.parse.urlparse(uri) + netloc = parts.netloc + self.host, _, self.port = netloc.partition(":") + + + def __enter__(self): + self.connect() + return self + + def __exit__(self, exc_typ, exc_val, exc_tb): + pass + + def connect(self): + self.socket = socket.socket() + self.socket.connect((self.host, int(self.port))) + + def disconnect(self): + pass + + def send(self, data): + self.socket.send(data) + +def connection(uri) -> Connection: + return Connection(uri) diff --git a/main.go b/main.go index 5411621..9b40c8e 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,42 @@ +// socket-server project main.go package main - -import "fmt" - +import ( + "fmt" + "net" + "os" +) +const ( + SERVER_HOST = "localhost" + SERVER_PORT = "9988" + SERVER_TYPE = "tcp" +) func main() { - fmt.Println("Hello World.") + fmt.Println("Server Running...") + server, err := net.Listen(SERVER_TYPE, SERVER_HOST+":"+SERVER_PORT) + if err != nil { + fmt.Println("Error listening:", err.Error()) + os.Exit(1) + } + defer server.Close() + fmt.Println("Listening on " + SERVER_HOST + ":" + SERVER_PORT) + fmt.Println("Waiting for client...") + for { + connection, err := server.Accept() + if err != nil { + fmt.Println("Error accepting: ", err.Error()) + os.Exit(1) + } + fmt.Println("client connected") + go processClient(connection) + } +} +func processClient(connection net.Conn) { + buffer := make([]byte, 1024) + mLen, err := connection.Read(buffer) + if err != nil { + fmt.Println("Error reading:", err.Error()) + } + fmt.Println("Received: ", string(buffer[:mLen])) + _, err = connection.Write([]byte("Thanks! Got your message:" + string(buffer[:mLen]))) + connection.Close() }