Go实战--实现一个并发时钟服务器(The way to go)
生命不止,继续 go go go !!! golang就是为高并发而生的,为我们提供了goroutines和channel。虽然前面博客的代码片段中也有用到这两个关键字,但是一直没有组织好语言,也没有能力把goroutines和channel写好,那么估计我们先用,然后再看看的理解。 goroutines package main
import (
"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 package main
import "fmt"
func main() {
messages := make(chan string)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
用了make声明,时引用类型。 顺序时钟服务器 package main
import (
"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:05n"))
if err != nil {
return
}
time.Sleep(1 * time.Second)
}
}
然后go build即可。 nc命令介绍 yum install nmap-ncat.x86_64 作用: 使用nc命令模拟client获得服务器时间 ./clock & 使用nc命令: nc localhost 8080
输出结果: 这是个顺序服务器,如果多个客户端连接的话,需要第一个结束后再执行第二个。 支持并发的始终服务器 package main
import (
"io"
"log"
"net"
"time"
)
func main() {
listener,err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
go handleConn(conn)
}
}
func handleConn(c net.Conn) {
defer c.Close()
for {
_,time.Now().Format("2006-01-02 15:04:05n"))
if err != nil {
return
}
time.Sleep(1 * time.Second)
}
}
运行结果: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |