Go实战--实现一个并发时钟服务器(The way to go)

来源:互联网 发布:磊科nw336驱动 mac 编辑:程序博客网 时间:2024/04/30 17:42

生命不止,继续 go go go !!!

golang就是为高并发而生的,为我们提供了goroutines和channel。虽然前面博客的代码片段中也有用到这两个关键字,但是一直没有组织好语言,也没有能力把goroutines和channel写好,那么估计我们先用,然后再看看的理解。

goroutines
A goroutine is a lightweight thread managed by the Go runtime.
几个关键字:轻量级,线程。

package mainimport (    "fmt"    "time")func say(s string) {    for i := 0; i < 5; i++ {        time.Sleep(100 * time.Millisecond)        fmt.Println(s)    }}func main() {    go say("world")    say("hello")}

区别:

f()     // call f(); wait for it to return  go f()  // create a new goroutine that calls f(); don't wait

channels
Channels are the pipes that connect concurrent goroutines.
几个关键字:管道 连接。

package mainimport "fmt"func main() {    messages := make(chan string)    go func() { messages <- "ping" }()    msg := <-messages    fmt.Println(msg)}

用了make声明,时引用类型。

顺序时钟服务器
之前的博客已经介绍了很多,如何使用net/http包来构建一个服务器,关于golang中time package在昨天的博客中也有介绍了。
TCP 服务器,直接上代码:

package mainimport (    "io"    "log"    "net"    "time")func main() {    listener, err := net.Listen("tcp", "localhost:8080")    if err != nil {        log.Fatal(err)    }    for {        conn, err := listener.Accept()        if err != nil {            log.Print(err)            continue        }        handleConn(conn)    }}func handleConn(c net.Conn) {    defer c.Close()    for {        _, err := io.WriteString(c, time.Now().Format("2006-01-02 15:04:05\n"))        if err != nil {            return        }        time.Sleep(1 * time.Second)    }}

然后go build即可。

nc命令介绍
centos上安装nc命令:

yum install nmap-ncat.x86_64

作用:
(1)实现任意TCP/UDP端口的侦听,nc可以作为server以TCP或UDP方式侦听指定端口
(2)端口的扫描,nc可以作为client发起TCP或UDP连接
(3)机器之间传输文件
(4)机器之间网络测速

使用nc命令模拟client获得服务器时间
后台运行服务器:

./clock &

使用nc命令:

nc localhost 8080

输出结果:
2017-06-22 13:28:41
2017-06-22 13:28:42
2017-06-22 13:28:43
2017-06-22 13:28:44
2017-06-22 13:28:45
2017-06-22 13:28:46
2017-06-22 13:28:47
2017-06-22 13:28:48
2017-06-22 13:28:49
2017-06-22 13:28:50
2017-06-22 13:28:51
….

这是个顺序服务器,如果多个客户端连接的话,需要第一个结束后再执行第二个。

支持并发的始终服务器
很简单,在上面的代码在handle中加入关键字go即可:

package mainimport (    "io"    "log"    "net"    "time")func main() {    listener, err := net.Listen("tcp", "localhost:8080")    if err != nil {        log.Fatal(err)    }    for {        conn, err := listener.Accept()        if err != nil {            log.Print(err)            continue        }        go handleConn(conn)    }}func handleConn(c net.Conn) {    defer c.Close()    for {        _, err := io.WriteString(c, time.Now().Format("2006-01-02 15:04:05\n"))        if err != nil {            return        }        time.Sleep(1 * time.Second)    }}

运行结果:
这里写图片描述

这里写图片描述

原创粉丝点击