Skip to content

Instantly share code, notes, and snippets.

@anyu
Last active March 19, 2022 20:46
Show Gist options
  • Save anyu/dfc569cbefe732847428b3a410c23256 to your computer and use it in GitHub Desktop.
Save anyu/dfc569cbefe732847428b3a410c23256 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"net"
)
// Test with TCP clients:
// $ echo "heyo" | nc localhost 9000
// $ telnet localhost 9000
func main() {
// listen for incoming requests on specified port
listener, err := net.Listen("tcp", ":9000")
if err != nil {
fmt.Println("error starting tcp server")
}
defer listener.Close()
// infinite loop to keep accepting new TCP clients
for {
// Accept returns the next connection to the listener
// conn implements both io.Reader/io.Writer interfaces
conn, err := listener.Accept()
if err != nil {
fmt.Println("error accepting requests")
}
io.WriteString(conn, fmt.Sprintf("Handling request from %s...", conn.RemoteAddr().String()))
// or go handle(conn) to handle concurrently
conn.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment