Skip to content

Instantly share code, notes, and snippets.

@rickt
Created June 23, 2014 16:54
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 rickt/61b8df1bb956467f9f0f to your computer and use it in GitHub Desktop.
Save rickt/61b8df1bb956467f9f0f to your computer and use it in GitHub Desktop.
example SERVER code that listens on a TCP socket & receives GOB-encoded data
package main
// use this with tcpgobclient.go
import (
"encoding/gob"
"fmt"
"net"
)
type P struct {
M, N int64
}
func handleConnection(conn net.Conn) {
dec := gob.NewDecoder(conn)
p := &P{}
dec.Decode(p)
fmt.Printf("Received : %+v\n", p)
fmt.Println("Max=", p.M, "Avail=", p.N)
}
func main() {
fmt.Println("start")
ln, err := net.Listen("tcp", ":7743")
if err != nil {
// handle error
}
for {
conn, err := ln.Accept() // this blocks until connection or error
if err != nil {
// handle error
continue
}
go handleConnection(conn) // a goroutine handles conn so that the loop can accept other connections
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment