balcony_weather_station/event_proxy/main.go
2025-09-15 20:53:58 +02:00

61 lines
1.3 KiB
Go

package main
import (
"fmt"
"net"
)
func main() {
addr := "192.168.1.153:8080"
fmt.Printf("Starting TCP server on port %s\n", addr)
//Address to bind to
//Resolve address
addr_, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
fmt.Printf("Error resolving address: %s", err.Error())
return
}
//Listen for incoming connections
listener, err := net.ListenTCP("tcp", addr_)
if err != nil {
fmt.Printf("Error starting server: %s", err.Error())
return
}
defer listener.Close()
for {
//Accept incoming connection
conn, err := listener.AcceptTCP()
if err != nil {
fmt.Printf("Error accepting connection: %s", err.Error())
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn *net.TCPConn) {
defer conn.Close()
fmt.Printf("New connection from %s\n", conn.RemoteAddr().String())
buffer := make([]byte, 1024)
for {
//Read up to 1024 bytes
n, err := conn.Read(buffer)
if err != nil {
fmt.Printf("Error reading from connection: %s", err.Error())
return
}
if n == 0 {
return
}
fmt.Printf("Received message: %s\n", string(buffer[:n]))
//Echo message back
// _, err = conn.Write(buffer[:n])
_, err = conn.Write([]byte("1"))
if err != nil {
fmt.Printf("Error writing to connection: %s", err.Error())
return
}
}
}