Go-Servers

u013344915 · · 751 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:u013344915

查看原文:Go-Servers

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

751 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传