Created
April 16, 2014 09:00
-
-
Save zgiber/10836860 to your computer and use it in GitHub Desktop.
TCP server example. (For better small little servers out there.)
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 ( | |
"io" | |
"log" | |
"net" | |
"time" | |
) | |
func main() { | |
run() | |
} | |
func run() { | |
log.Println("listening") | |
l, err := net.Listen("tcp", "0.0.0.0:5000") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer l.Close() | |
for { | |
// Wait for a connection. | |
conn, err := l.Accept() | |
if err != nil { | |
continue | |
} | |
go handleConn(conn) | |
} | |
} | |
func handleConn(conn net.Conn) { | |
for { | |
data := make([]byte, 512) | |
readLength, err := conn.Read(data) | |
if err != nil { | |
log.Println(err) | |
// check for EOF | |
if err == io.EOF { | |
conn.Close() | |
return | |
} | |
// check for timeout | |
if neterr, ok := err.(net.Error); ok && neterr.Timeout() { | |
conn.Close() | |
return | |
} | |
continue | |
} | |
// set timeout whenever receiving new data | |
conn.SetDeadline(time.Now().Add(60 * time.Second)) | |
log.Print(string(data)[:readLength]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It just writes the stuff to the console. Handy for testing.