reso-execution/cmd/client/main.go
2024-03-16 17:15:27 -07:00

100 lines
2.2 KiB
Go

package main
import (
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
func main() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
host := "127.0.0.1:5000"
langURL := fmt.Sprintf("ws://%s/lang", host)
cmdURL := fmt.Sprintf("ws://%s/cmd", host)
debugURL := fmt.Sprintf("ws://%s/debug", host)
execURL := fmt.Sprintf("ws://%s/", host)
execConn, err := connectWebSocket(execURL)
if err != nil {
log.Fatal("Failed to connect to lang websocket:", err)
}
defer execConn.Close()
langConn, err := connectWebSocket(langURL)
if err != nil {
log.Fatal("Failed to connect to lang websocket:", err)
}
defer langConn.Close()
cmdConn, err := connectWebSocket(cmdURL)
if err != nil {
log.Fatal("Failed to connect to cmd websocket:", err)
}
defer cmdConn.Close()
debugConn, err := connectWebSocket(debugURL)
if err != nil {
log.Fatal("Failed to connect to debug websocket:", err)
}
defer debugConn.Close()
done := make(chan struct{})
go readMessages(langConn, "lang", done)
go readMessages(cmdConn, "cmd", done)
go readMessages(debugConn, "debug", done)
// Read the contents of source.txt
sourceFile := "source.txt"
sourceData, err := ioutil.ReadFile(sourceFile)
if err != nil {
log.Fatal("Failed to read source file:", err)
}
// create execConn off of / endpoint
// Send the contents over the lang websocket
err = execConn.WriteMessage(websocket.TextMessage, sourceData)
if err != nil {
log.Fatal("Failed to send source data over lang websocket:", err)
}
select {
case <-interrupt:
fmt.Println("Interrupt signal received, closing connections...")
close(done)
time.Sleep(1 * time.Second)
return
}
}
func connectWebSocket(urlStr string) (*websocket.Conn, error) {
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
return nil, err
}
return conn, nil
}
func readMessages(conn *websocket.Conn, name string, done chan struct{}) {
for {
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("Error reading message from", name, "websocket:", err)
return
}
fmt.Printf("Received message from %s: %s\n", name, message)
}
}