Skip to content

Instantly share code, notes, and snippets.

@GuoJing
Created December 23, 2015 12:06
Show Gist options
  • Save GuoJing/c78a9c946162acebc2c3 to your computer and use it in GitHub Desktop.
Save GuoJing/c78a9c946162acebc2c3 to your computer and use it in GitHub Desktop.
simple socket server with keepalive
package main
import (
"fmt"
"net"
"os"
"time"
)
func main() {
service := ":55555"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go handleClient(conn)
}
}
func handleClient(conn net.Conn) {
conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
buffer := make([]byte, 1024)
defer conn.Close()
for {
read_len, err := conn.Read(buffer)
if err != nil {
break
}
message := string(buffer[:read_len])
if read_len == 0 {
break
} else {
ret := message + "too!"
conn.Write([]byte(ret))
}
}
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment