First commit

This commit is contained in:
DirtyDuckEUW 2025-05-29 04:30:53 +02:00
parent b378377069
commit deb52470e5
5 changed files with 134 additions and 0 deletions

44
Client.go Normal file
View file

@ -0,0 +1,44 @@
package main
import (
"fmt"
"net"
"strconv"
"time"
)
const PAYLOAD = "Test data"
func StartClient() net.Conn {
conn := SetupClient(HOST, PORT)
return conn
}
func SetupClient(host string, port string) net.Conn {
// Connect to the server
conn, err := net.Dial("tcp", host+":"+port)
if err != nil {
fmt.Println(err)
return nil
}
SendData(conn)
return conn
}
func SendData(conn net.Conn) {
counter := 0
for counter < 10 {
// Send some data to the server
_, err := conn.Write([]byte(PAYLOAD + " " + strconv.Itoa(counter)))
if err != nil {
fmt.Println(err)
return
}
counter++
time.Sleep(100 * time.Millisecond)
}
}

View file

@ -0,0 +1,31 @@
package main
import (
"fmt"
"net"
"time"
)
const HOST = "localhost"
const PORT = "8080"
// Hello returns a greeting for the named person.
func main() {
go startServer()
time.Sleep(1 * time.Second)
client := StartClient()
closeConnection("Client", client)
time.Sleep(1 * time.Second)
}
func log(msg string) {
fmt.Println(time.Now().Format(time.RFC822) + " " + msg)
}
func closeConnection(id string, conn net.Conn) {
log(id + " connection closed: " + conn.LocalAddr().String())
conn.Close()
}

54
Server.go Normal file
View file

@ -0,0 +1,54 @@
package main
import (
"fmt"
"net"
)
func startServer() net.Conn {
return setupServer(PORT)
}
func setupServer(port string) net.Conn {
// Listen for incoming connections on port 8080
ln, err := net.Listen("tcp", ":"+port)
if err != nil {
log(err.Error())
return nil
}
// Accept incoming connections and handle them
for {
conn, err := ln.Accept()
if err != nil {
log(err.Error())
continue
}
// Handle the connection in a new goroutine
go handleConnection(conn)
return conn
}
}
func handleConnection(conn net.Conn) {
// Close the connection when we're done
defer closeConnection("Server", conn)
for {
// Read incoming data
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
//read = false
log(err.Error())
return
}
// Print the incoming data
fmt.Printf("Received: %s \n", buf)
}
}

2
build.cmd Normal file
View file

@ -0,0 +1,2 @@
go mod tidy
go build

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module networkstats
go 1.24.3