Skip to content

Instantly share code, notes, and snippets.

@MilosSimic
Forked from L1fescape/simple-tcp-server.go
Created January 25, 2019 22:15
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 MilosSimic/2ce53d8abed78d701cc10b61609b1c22 to your computer and use it in GitHub Desktop.
Save MilosSimic/2ce53d8abed78d701cc10b61609b1c22 to your computer and use it in GitHub Desktop.
package main
import (
"net"
"strings"
"fmt"
)
func handleConnection(conn net.Conn) {
// try to read data from the connection
data := make([]byte, 512)
n, err := conn.Read(data)
if err != nil { panic(err) }
s := string(data[:n])
// print the request data
fmt.Println(s)
// send a response
var resp = []string{"Hi", "there!"}
var str = strings.Join(resp, " ")
_, err = conn.Write([]byte(str))
if err != nil { panic(err) }
// close the connection
conn.Close()
}
func main() {
ln, err := net.Listen("tcp", ":8081")
if err != nil {
// handle error
}
for {
conn, err := ln.Accept()
if err != nil {
// handle error
continue
}
go handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment