Created
December 23, 2015 12:06
-
-
Save GuoJing/c78a9c946162acebc2c3 to your computer and use it in GitHub Desktop.
simple socket server with keepalive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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