75 lines
1.5 KiB
Go
75 lines
1.5 KiB
Go
package net
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"sync"
|
|
)
|
|
|
|
// Start Starts the TCP server on the specified address.
|
|
func Start(addr string, stopChan <-chan struct{}, wg *sync.WaitGroup) {
|
|
defer wg.Done()
|
|
|
|
// Start listening on the specified address
|
|
listener, err := net.Listen("tcp", addr)
|
|
if err != nil {
|
|
_, err := fmt.Fprintf(os.Stderr, "Error starting TCP server: %v", err)
|
|
if err != nil {
|
|
return
|
|
}
|
|
return
|
|
}
|
|
|
|
// Close the listener when the application closes.
|
|
defer func(listener net.Listener) {
|
|
err := listener.Close()
|
|
if err != nil {
|
|
return
|
|
}
|
|
}(listener)
|
|
|
|
fmt.Printf("TCP server listening on %s\n", addr)
|
|
|
|
// Listen for an incoming connection in a goroutine.
|
|
go func() {
|
|
for {
|
|
conn, err := listener.Accept()
|
|
if err != nil {
|
|
select {
|
|
case <-stopChan:
|
|
return // Safe exit if stop has been signalled
|
|
default:
|
|
fmt.Fprintf(os.Stderr, "Error accepting connection: %v", err)
|
|
}
|
|
continue
|
|
}
|
|
|
|
// Handle connections in a new goroutine.
|
|
go handleRequest(conn)
|
|
}
|
|
}()
|
|
|
|
// Block until we receive a stop signal
|
|
<-stopChan
|
|
}
|
|
|
|
// handleRequest handles incoming requests.
|
|
func handleRequest(conn net.Conn) {
|
|
// Close the connection when you're done with it.
|
|
defer conn.Close()
|
|
|
|
// Make a buffer to hold incoming data.
|
|
buf := make([]byte, 1024)
|
|
|
|
// Read the incoming connection into the buffer.
|
|
_, err := conn.Read(buf)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error reading: %v", err)
|
|
return
|
|
}
|
|
|
|
// Send a response back to person contacting us.
|
|
conn.Write([]byte("Hello, World!\n"))
|
|
}
|