iris通用html,【GO】13.Iris WebSocket 实例

iris websocket服务端

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{

ReadBufferSize: 1024,

WriteBufferSize: 1024,

})

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", websocket.ClientHandler())

}

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)

})

}

客户端html页面websockets.html

Send

启动服务端后,打开三个localhost:8080页面

1号页面输入我是1号

2号页面输入我是2号

3号页面输入我是3号

三个页面分别显示如下:

c4e6dac2e7e2c2974673e485f19bcd61.png

e4ef84664897e4c6f6b0148e2abe714c.png

0c46beae5539c2c281181a86ec158851.png

0258e01aa3a526edda0f5ca5a68f686b.png

代码来自官方https://github.com/kataras/iris

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值