Working simple client/server

This commit is contained in:
Eli Ribble 2023-06-19 16:09:19 -07:00
parent 0d33aacf3f
commit e155420a4b
3 changed files with 82 additions and 4 deletions

14
client.py Normal file
View File

@ -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()

29
datajack/__init__.py Normal file
View File

@ -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)

43
main.go
View File

@ -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()
}