Last active
March 19, 2022 20:46
-
-
Save anyu/dfc569cbefe732847428b3a410c23256 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"io" | |
"net" | |
) | |
// Test with TCP clients: | |
// $ echo "heyo" | nc localhost 9000 | |
// $ telnet localhost 9000 | |
func main() { | |
// listen for incoming requests on specified port | |
listener, err := net.Listen("tcp", ":9000") | |
if err != nil { | |
fmt.Println("error starting tcp server") | |
} | |
defer listener.Close() | |
// infinite loop to keep accepting new TCP clients | |
for { | |
// Accept returns the next connection to the listener | |
// conn implements both io.Reader/io.Writer interfaces | |
conn, err := listener.Accept() | |
if err != nil { | |
fmt.Println("error accepting requests") | |
} | |
io.WriteString(conn, fmt.Sprintf("Handling request from %s...", conn.RemoteAddr().String())) | |
// or go handle(conn) to handle concurrently | |
conn.Close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment