Skip to content

Instantly share code, notes, and snippets.

@physacco
Created March 8, 2013 03:00
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 physacco/5113904 to your computer and use it in GitHub Desktop.
Save physacco/5113904 to your computer and use it in GitHub Desktop.
A TCP echo server demo.
package main
import (
"os"
"fmt"
"net"
"bufio"
)
func handleConnection(conn net.Conn) {
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("ReadString error: %s\n", err)
conn.Close()
break
}
fmt.Printf("[Client] %s", line)
writer.WriteString("[Server] " + line)
writer.Flush()
}
}
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:4567")
if err != nil {
fmt.Printf("Listen error: %s\n", err)
os.Exit(1)
}
for {
fmt.Printf("Accepting new connections...\n")
conn, err := ln.Accept()
if err != nil {
fmt.Printf("Accept error: %s\n", err)
continue
}
go handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment