[日常] Go语言圣经--示例: 并发的Echo服务

最简单的回声服务器:

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) //新建goroutines处理连接
    }   

}

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

原理:

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

2.net.Conn类型type Conn interface { Read(b []byte) (n int,err error) Write(b []byte) (n int,err error) ...}一个类型如果拥有一个接口需要的所有方法,那么这个类型就实现了这个接口

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

升级版,每条连接一个goroutine,每个goroutine中分出多个输出goroutine

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

func main() {
listener,connection aborted
continue
}
go handleConn(conn) //新建goroutines处理连接
}
}

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,shout)
time.Sleep(delay)
fmt.Fprintln(c,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

也用到了大量的7.3节 实现接口的条件

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...