-
-
Save feix/5f3ac7a549fb10744991f4355f73b4ab to your computer and use it in GitHub Desktop.
Golang example on handling TCP connection and setting timeout.
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" | |
"time" | |
"bufio" | |
) | |
func handleConnection(conn net.Conn) { | |
fmt.Println("Handling new connection...") | |
// Close connection when this function ends | |
defer func() { | |
fmt.Println("Closing connection...") | |
conn.Close() | |
}() | |
timeoutDuration := 5 * time.Second | |
bufReader := bufio.NewReader(conn) | |
for { | |
// Set a deadline for reading. Read operation will fail if no data | |
// is received after deadline. | |
conn.SetReadDeadline(time.Now().Add(timeoutDuration)) | |
// Read tokens delimited by newline | |
bytes, err := bufReader.ReadBytes('\n') | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("%s", bytes) | |
} | |
} | |
func main() { | |
// Start listening to port 8888 for TCP connection | |
listener, err:= net.Listen("tcp", ":8888") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer func() { | |
listener.Close() | |
fmt.Println("Listener closed") | |
}() | |
for { | |
// Get net.TCPConn object | |
conn, err := listener.Accept() | |
if err != nil { | |
fmt.Println(err) | |
break | |
} | |
go handleConnection(conn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment