mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-11 14:22:49 +00:00
good good study, day day up!
This commit is contained in:
51
vendor/gopl.io/ch8/reverb2/reverb.go
generated
vendored
Normal file
51
vendor/gopl.io/ch8/reverb2/reverb.go
generated
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 224.
|
||||
|
||||
// Reverb2 is a TCP server that simulates an echo.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func echo(c net.Conn, shout string, delay time.Duration) {
|
||||
fmt.Fprintln(c, "\t", strings.ToUpper(shout))
|
||||
time.Sleep(delay)
|
||||
fmt.Fprintln(c, "\t", shout)
|
||||
time.Sleep(delay)
|
||||
fmt.Fprintln(c, "\t", strings.ToLower(shout))
|
||||
}
|
||||
|
||||
//!+
|
||||
func handleConn(c net.Conn) {
|
||||
input := bufio.NewScanner(c)
|
||||
for input.Scan() {
|
||||
go echo(c, input.Text(), 1*time.Second)
|
||||
}
|
||||
// NOTE: ignoring potential errors from input.Err()
|
||||
c.Close()
|
||||
}
|
||||
|
||||
//!-
|
||||
|
||||
func main() {
|
||||
l, err := net.Listen("tcp", "localhost:8000")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for {
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
log.Print(err) // e.g., connection aborted
|
||||
continue
|
||||
}
|
||||
go handleConn(conn)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user