[Daily] Go Language Bible--Example: Concurrent Echo Service

Simplest echo server:

package main

import (
        "io"
        "net"
        "log"
)


func main() {
        listener, err := net.Listen("tcp", ":8040")
        if err != nil {
                log.Fatal(err)
        }   

        for {
                conn, err := listener.Accept()
                if err != nil {
                        log.Print(err) // e.g., connection aborted
                        continue
                }   
                go handleConn(conn) //Create new goroutines to handle the connection
        }   
}

func handleConn(c net.Conn) {
    io.Copy(c, c) // NOTE: ignoring errors
    c.Close()
}

principle:

1.io.Copy()方法
func Copy(dst Writer, src Reader) (written int64, err error)

2.net.Conn type
type Conn interface {
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
...
}
If a type has a required interface All methods, then this type implements this interface

3.io.Writer
type Writer interface {
Write(p []byte) (n int, err error)
}
4.io.Reader
type Reader interface {
Read(p []byte) (n int, err error)
}

Upgraded version, one goroutine per connection, and multiple output goroutines in each goroutine

package main

import (
        "bufio"
        "fmt"
        "log"
        "net"
        "strings"
        "time"
)

func main() {
        listener, err := net.Listen("tcp", ":8040")
        if err != nil {
                log.Fatal(err)
        }   

        for {
                conn, err := listener.Accept()
                if err != nil {
                        log.Print(err) // e.g., connection aborted
                        continue
                }   
                go handleConn(conn) //Create new goroutines to handle the connection
        }   
}

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 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))
}

  

1.fmt.Fprintln()
func Fprintln(w io.Writer, a ...interface{}) (n int, err error)

2.bufio.NewScanner()
func NewScanner(r io.Reader) *Scanner
func (s *Scanner) Scan() bool
func (s *Scanner) Text() string

It also uses a lot of conditions for implementing the interface in Section 7.3

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324990050&siteId=291194637