您的位置:首页 > 编程语言 > Go语言

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  服务器 socket Go