Created
July 23, 2012 16:18
-
-
Save jsanders/3164500 to your computer and use it in GitHub Desktop.
Simple echo server in Go
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" | |
"net" | |
"os" | |
"bufio" | |
) | |
func printBanner() { | |
fmt.Printf("[%d] Server started, ConnectionSharer version 0.0.1\n", os.Getpid()) | |
} | |
func createListener() net.Listener { | |
port := "9999" | |
listener, err := net.Listen("tcp", ":"+port) | |
if err != nil { | |
fmt.Println("Error on listen: ", err.Error()) | |
os.Exit(1) | |
} | |
fmt.Println("The server is now ready to accept connections on port", port) | |
return listener | |
} | |
func acceptConnection(listener net.Listener) net.Conn { | |
connection, err := listener.Accept() | |
if err != nil { | |
fmt.Println("Error on accept: ", err.Error()) | |
os.Exit(1) | |
} | |
fmt.Println("Accepted", connection.RemoteAddr().String()) | |
return connection | |
} | |
func handleConnection(conn net.Conn) { | |
defer conn.Close() | |
for { | |
if shouldQuit := handle(conn); shouldQuit { | |
return | |
} | |
} | |
} | |
func handle(conn net.Conn) (shouldQuit bool) { | |
r := bufio.NewReader(conn) | |
w := bufio.NewWriter(conn) | |
line, err := r.ReadString('\n') | |
if err != nil { | |
fmt.Println("Error reading line: ", err) | |
return true | |
} | |
fmt.Print("Got line: ", line) | |
w.WriteString(line) | |
w.Flush() | |
return false | |
} | |
func main() { | |
printBanner() | |
listener := createListener() | |
defer listener.Close() | |
for { | |
conn := acceptConnection(listener) | |
go handleConnection(conn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment