Skip to content

Instantly share code, notes, and snippets.

@jnovikov
Created April 21, 2019 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnovikov/f92d2e9a125c9df9f7e7a1fb4ed83ba4 to your computer and use it in GitHub Desktop.
Save jnovikov/f92d2e9a125c9df9f7e7a1fb4ed83ba4 to your computer and use it in GitHub Desktop.
Golang tcp server example
package main
import (
"fmt"
"net"
)
func handleConnection(c net.Conn) {
var s string
n, _ := fmt.Fscan(c, &s)
if n <= 0 {
fmt.Fprintln(c, "Please type something")
} else {
fmt.Fprintln(c, "Hello, " + s)
}
c.Close()
}
func main() {
l, err := net.Listen("tcp", "127.0.0.1:5005")
if err != nil {
panic(err)
}
defer l.Close()
fmt.Printf("%v", l.Addr())
for {
conn, err := l.Accept()
if err != nil {
fmt.Println(err)
}
handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment