Go语言Web : Websockets

go语言如何使用websockets,为每一个请求随意返还一些数据,不需要任何第三方库,只要adaptors/websocket,但是如果你想使用其他的方法,记住,Iris是完全兼容的标准库。

在这里有更多websocket范例。

// websockets.go
package main

import (
    "fmt"

    "gopkg.in/kataras/iris.v6"
    "gopkg.in/kataras/iris.v6/adaptors/httprouter"
    "gopkg.in/kataras/iris.v6/adaptors/websocket"
)

func handleConnection(c websocket.Connection) {

    // 读取浏览器发生的事件
    c.On("chat", func(msg string) {

        // 输出消息到控制台
        fmt.Printf("%s sent: %s\n", c.Context().RemoteAddr(), msg)

        // 返回数据给浏览器
        c.Emit("chat", msg)
    })

}

func main() {
    app := iris.New()
    app.Adapt(httprouter.New())

    // 创建一个echo路径的websocket服务
    ws := websocket.New(websocket.Config{
        ReadBufferSize:  1024,
        WriteBufferSize: 1024,
        Endpoint:        "/echo",
    })

    ws.OnConnection(handleConnection)

    // 配置websocket服务
    // 当然,你可以配置更多的websocket服务
    app.Adapt(ws)

    app.Get("/", func(ctx *iris.Context) {
        ctx.ServeFile("websockets.html", false) // second parameter: enable gzip?
    })

    app.Listen(":8080")
}
<!-- websockets.html -->
<input id="input" type="text" />
<button onclick="send()">Send</button>
<pre id="output"></pre>
<script src="/iris-ws.js"></script>
<script>
    var input = document.getElementById("input");
    var output = document.getElementById("output");

    // Ws comes from the auto-served '/iris-ws.js'
    var socket = new Ws("ws://localhost:8080/echo");
    socket.OnConnect(function () {
        output.innerHTML += "Status: Connected\n";
    });

    socket.OnDisconnect(function () {
        output.innerHTML += "Status: Disconnected\n";
    });

    // 读取服务器发生的事件
    socket.On("chat", function (msg) {
        output.innerHTML += "Server: " + msg + "\n";
    });

    function send() {
        // 发送
        socket.Emit("chat", input.value);
        input.value = "";
    }
</script>
$ go run websockets.go
[127.0.0.1]:53403 sent: Hello Go Web Examples, you're doing great!

Status: Connected

Server: Hello Go Web Examples, you're doing great!

results matching ""

    No results matching ""