Go-Servers
2016-09-05 18:08
316 查看
tcp
Go简化了传统的socket处理步骤:- 服务器端的流程:Listen->Accept(->Decode->Close)
- 客户端的流程:Dial->Encode->Close
package main import ( "fmt" "encoding/gob" "net" "time" ) func server() { // listen on a port listen, err := net.Listen("tcp", ":9999") if err != nil { fmt.Println(err) return } for { // accept a connection connection, err := listen.Accept() if err != nil { fmt.Println(err) continue } // handle the connection go handleServerConnection(connection) } } func handleServerConnection(connection net.Conn) { // receive the message var msg string err := gob.NewDecoder(connection).Decode(&msg) if err != nil { fmt.Println(err) } else { fmt.Println("Received: ", msg) } connection.Close() } func client() { // connect to the server connection, err := net.Dial("tcp", "127.0.0.1:9999") if err != nil { fmt.Println(err) return } // send the message msg := "Hello, world!" fmt.Println("Sending: ", msg) err = gob.NewEncoder(connection).Encode(msg) if err != nil { fmt.Println(err) } connection.Close() } /* D:\examples>go run helloworld.go Sending: Hello, world! Sending: Hello, world! Sending: Hello, world! Received: Hello, world! Received: Hello, world! Sending: Hello, world! Received: Hello, world! Sending: Hello, world! Received: Hello, world! Received: Hello, world! D:\examples> */ func main() { go server() for i := 0; i < 5; i++ { go client() time.Sleep(10000) } var input string fmt.Scanln(&input) }
HTTP
下面是动态网页的示例。这种做法和Java Servlet HttpServlet是一致的,但如何实现MVC,则超出Introducing Go的范围。package main import ( //"fmt" "net/http" "io" ) func hello(res http.ResponseWriter, req *http.Request) { res.Header().Set("Content-Type", "text/html") io.WriteString( res, `<DOCTYPE html> <html> <head> <title>Hello, World</title> </head> <body> Hello, World! </body> </html>`, ) } func main() { http.HandleFunc("/hello", hello) http.ListenAndServe(":9000", nil) }
代码运行后,在浏览器输入http://localhost:9000/hello,则浏览器会显示Hello, World!。
处理静态文件:
http.Handle( "/assets/", http.StripPrefix( "/assets/", http.FileServer(http.Dir("assets")), ), )
RPC
略相关文章推荐
- A Tour of Go Web servers
- 丛林小英雄迪亚哥 Go Diego Go 14张DVD,朵拉的表兄弟
- Go2Shell
- Go语言之旅[二]
- Google公布实现Go 1.5自举的计划
- [go]golang snmp测试(1)
- Tecnico Prevencion de riesgos profesionales: ya sabes!!! La unica manera de comenzar a trabajar en el entorno de la prevencion d
- 对Golang有兴趣的朋友,推荐一款go语言Web框架-dotweb
- Go的位操作
- go安装
- Javascript:history.go()和history.back()的用法和区别
- 【寒江雪】Go实现工厂模式
- T-SQL中GO关键字
- Go语言学习笔记(六)-方法和接口
- 【寒江雪】Go实现Builder Pattern
- 从nsq中学习如何优雅的退出go 网络程序
- go语言list循环删除元素(转载)
- Go语言中slice作为参数传递时遇到的一些“坑”
- 持续交付工具ThoughtWorks Go部署step by step