Go-Servers

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值