1 Star 2 Fork 0

api-go/iris

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
main.go 1.65 KB
一键复制 编辑 原始数据 按行查看 历史
package main
import (
"fmt"
"github.com/kataras/iris"
"github.com/kataras/iris/websocket"
)
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.ServeFile("websockets.html", false) // second parameter: enable gzip?
})
setupWebsocket(app)
// x2
// http://localhost:8080
// http://localhost:8080
// write something, press submit, see the result.
app.Run(iris.Addr(":8080"))
}
func setupWebsocket(app *iris.Application) {
// create our echo websocket server
ws := websocket.New(websocket.Config{
// These are low-level optionally fields,
// user/client can't see those values.
ReadBufferSize: 1024,
WriteBufferSize: 1024,
// only javascript client-side code has the same rule,
// which you serve using the ws.ClientSource (see below).
EvtMessagePrefix: []byte("my-custom-prefix:"),
})
ws.OnConnection(handleConnection)
// register the server on an endpoint.
// see the inline javascript code in the websockets.html, this endpoint is used to connect to the server.
app.Get("/echo", ws.Handler())
// serve the javascript built'n client-side library,
// see websockets.html script tags, this path is used.
app.Any("/iris-ws.js", func(ctx iris.Context) {
ctx.Write(ws.ClientSource)
})
}
func handleConnection(c websocket.Connection) {
// Read events from browser
c.On("chat", func(msg string) {
// Print the message to the console, c.Context() is the iris's http context.
fmt.Printf("%s sent: %s\n", c.Context().RemoteAddr(), msg)
// Write message back to the client message owner with:
// c.Emit("chat", msg)
// Write message to all except this client with:
c.To(websocket.Broadcast).Emit("chat", msg)
})
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/netscript/iris.git
git@gitee.com:netscript/iris.git
netscript
iris
iris
v11.1.0

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385