Skip to content

Instantly share code, notes, and snippets.

@dbehnke
Created March 31, 2014 15:16
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 dbehnke/9894699 to your computer and use it in GitHub Desktop.
Save dbehnke/9894699 to your computer and use it in GitHub Desktop.
a work in progress.. simple tcp server in go.
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"net"
"time"
)
const (
//tcp port to listen on
port = ":4111"
//timeout for read operations
read_timeout = 30
)
func readline(c net.Conn, buf *bufio.ReadWriter) (d []byte, err error) {
//wrapper for buf.ReadLine to set a deadline timeout
c.SetReadDeadline(time.Now().Add(time.Second * read_timeout))
d, _, err = buf.ReadLine()
return
}
func writeline(c net.Conn, buf *bufio.ReadWriter,
s string) (err error) {
_, err = buf.WriteString(fmt.Sprintf("%s\r\n", s))
if err != nil {
return
}
err = buf.Flush()
return
}
func client_handler(c net.Conn) {
defer c.Close()
buf := bufio.NewReadWriter(bufio.NewReader(c), bufio.NewWriter(c))
//client echo loop
for {
d, err := readline(c, buf)
if err != nil {
log.Printf("ERR Reading from Client: %s", err)
return
}
log.Printf("RECV: [%s] (%d bytes)\n", d, len(d))
//echo back what we received
err = writeline(c, buf, fmt.Sprintf("Received: [%s]\r\n", d))
if err != nil {
log.Printf("ERR Writing to Client: %s", err)
return
}
s := string(d)
if s == "BYE" {
writeline(c, buf, "BYE!")
return
}
}
}
func listen() {
// Seed the Random Generator
rand.Seed(time.Now().UTC().UnixNano())
l, err := net.Listen("tcp", port)
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
// Wait for a connection.
c, err := l.Accept()
if err != nil {
log.Fatal(err)
}
// Handle the connection in a new goroutine.
// The loop then returns to accepting, so that
// multiple connections may be served concurrently.
go client_handler(c)
}
}
func main() {
listen()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment