-
-
Save garsue/51028b0021fa05708add589421c2ba17 to your computer and use it in GitHub Desktop.
A simple echo server testing a few interesting Go language features, goroutines and channels.
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 ( | |
"bufio" | |
"fmt" | |
"net" | |
"strconv" | |
) | |
const port = 3540 | |
func main() { | |
server, err := net.Listen("tcp", ":"+strconv.Itoa(port)) | |
if server == nil { | |
panic("couldn't start listening: " + err.Error()) | |
} | |
conns := clientConns(server) | |
for { | |
go handleConn(<-conns) | |
} | |
} | |
func clientConns(listener net.Listener) chan net.Conn { | |
ch := make(chan net.Conn) | |
i := 0 | |
go func() { | |
for { | |
client, err := listener.Accept() | |
if client == nil { | |
fmt.Printf("couldn't accept: " + err.Error()) | |
continue | |
} | |
i++ | |
fmt.Printf("%d: %v <-> %v\n", i, client.LocalAddr(), client.RemoteAddr()) | |
ch <- client | |
} | |
}() | |
return ch | |
} | |
func handleConn(client net.Conn) { | |
b := bufio.NewReader(client) | |
for { | |
line, err := b.ReadBytes('\n') | |
if err != nil { // EOF, or worse | |
break | |
} | |
fmt.Print(string(line)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment