mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-11-13 09:16:10 +08:00
更新14、15和17章目录 (#702)
* 更新14、15和17章目录 * Update README.md * 添加章节序号 * 添加章节序号 * 添加代码链接 * 修改错别字 * 删除多余字符 * 修复代码与文件不对应的问题 * 修改代码
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
|
||||
客户端-服务器应用正是 goroutines 和 channels 的亮点所在。
|
||||
|
||||
客户端(Client)可以是运行在任意设备上的任意程序,它会按需发送请求(request)至服务器。服务器(Server)接收到这个请求后开始相应的工作,然后再将响应(response)返回给客户端。典型情况下一般是多个客户端(既多个请求)对应一个(或少量)服务器。例如我们日常使用的浏览器客户端,其功能就是向服务器请求网页。而Web服务器则会向浏览器响应网页数据。
|
||||
客户端(Client)可以是运行在任意设备上的任意程序,它会按需发送请求(request)至服务器。服务器(Server)接收到这个请求后开始相应的工作,然后再将响应(response)返回给客户端。典型情况下一般是多个客户端(即多个请求)对应一个(或少量)服务器。例如我们日常使用的浏览器客户端,其功能就是向服务器请求网页。而Web服务器则会向浏览器响应网页数据。
|
||||
|
||||
使用Go的服务器通常会在协程中执行向客户端的响应,故而会对每一个客户端请求启动一个协程。一个常用的操作方法是客户端请求自身中包含一个通道,而服务器则向这个通道发送响应。
|
||||
|
||||
@@ -35,7 +35,7 @@ func run(op binOp, req *Request) {
|
||||
req.replyc <- op(req.a, req.b)
|
||||
}
|
||||
```
|
||||
`server`协程会无限循环以从`chan \*Request`接收请求,并且为了避免被长时间操作所堵塞,它将为每一个请求启动一个协程来做具体的工作:
|
||||
`server`协程会无限循环以从`chan *Request`接收请求,并且为了避免被长时间操作所堵塞,它将为每一个请求启动一个协程来做具体的工作:
|
||||
|
||||
```go
|
||||
func server(op binOp, service chan *Request) {
|
||||
@@ -112,26 +112,22 @@ func run(op binOp, req *Request) {
|
||||
req.replyc <- op(req.a, req.b)
|
||||
}
|
||||
|
||||
func server(op binOp, service chan *Request, quit chan bool) {
|
||||
func server(op binOp, service chan *Request) {
|
||||
for {
|
||||
select {
|
||||
case req := <-service:
|
||||
go run(op, req)
|
||||
case <-quit:
|
||||
return
|
||||
}
|
||||
req := <-service // requests arrive here
|
||||
// start goroutine for request:
|
||||
go run(op, req) // don't wait for op
|
||||
}
|
||||
}
|
||||
|
||||
func startServer(op binOp) (service chan *Request, quit chan bool) {
|
||||
service = make(chan *Request)
|
||||
quit = make(chan bool)
|
||||
go server(op, service, quit)
|
||||
return service, quit
|
||||
func startServer(op binOp) chan *Request {
|
||||
reqChan := make(chan *Request)
|
||||
go server(op, reqChan)
|
||||
return reqChan
|
||||
}
|
||||
|
||||
func main() {
|
||||
adder, quit := startServer(func(a, b int) int { return a + b })
|
||||
adder := startServer(func(a, b int) int { return a + b })
|
||||
const N = 100
|
||||
var reqs [N]Request
|
||||
for i := 0; i < N; i++ {
|
||||
@@ -149,9 +145,9 @@ func main() {
|
||||
fmt.Println("Request ", i, " is ok!")
|
||||
}
|
||||
}
|
||||
quit <- true
|
||||
fmt.Println("done")
|
||||
}
|
||||
|
||||
```
|
||||
## 14.10.2 卸载(Teardown):通过信号通道关闭服务器
|
||||
|
||||
|
||||
Reference in New Issue
Block a user