Skip to content

Instantly share code, notes, and snippets.

@dima056359
Created May 27, 2017 21:50
Show Gist options
  • Save dima056359/e7c1892a0073e557750d3b965b5c46df to your computer and use it in GitHub Desktop.
Save dima056359/e7c1892a0073e557750d3b965b5c46df to your computer and use it in GitHub Desktop.
Simple echo-server written in Golang
package main
import (
"log"
"net"
"strings"
)
// accepting connections
func main() {
ln, err := net.Listen("tcp", ":6000")
if err != nil {
log.Fatal(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handleConnection(conn)
}
}
// handling the connection
func handleConnection(c net.Conn) {
buf := make([]byte, 4096)
for {
n, err := c.Read(buf)
if err != nil || n == 0 {
c.Close()
break
}
n, err = c.Write(buf[0:n])
// push received message to the screen
log.Println(strings.TrimSpace(string(buf[:n])))
if err != nil {
c.Close()
break
}
}
log.Printf("Connection from %v closed.", c.RemoteAddr())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment