1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-30 04:41:27 +00:00
Beego/example/chat/controllers/ws.go

181 lines
4.0 KiB
Go
Raw Normal View History

2014-04-12 05:18:18 +00:00
// Beego (http://beego.me/)
// @description beego is an open-source, high-performance web framework for the Go programming language.
// @link http://github.com/astaxie/beego for the canonical source repository
// @license http://github.com/astaxie/beego/blob/master/LICENSE
// @authors Unknwon
2013-09-10 10:38:40 +00:00
package controllers
import (
"io/ioutil"
"math/rand"
"net/http"
"time"
2013-12-30 14:51:54 +00:00
"github.com/astaxie/beego"
"github.com/gorilla/websocket"
2013-09-10 10:38:40 +00:00
)
const (
// Time allowed to write a message to the client.
writeWait = 10 * time.Second
// Time allowed to read the next message from the client.
readWait = 60 * time.Second
// Send pings to client with this period. Must be less than readWait.
pingPeriod = (readWait * 9) / 10
// Maximum message size allowed from client.
maxMessageSize = 512
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
go h.run()
}
// connection is an middleman between the websocket connection and the hub.
type connection struct {
username string
// The websocket connection.
ws *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
}
// readPump pumps messages from the websocket connection to the hub.
func (c *connection) readPump() {
defer func() {
h.unregister <- c
c.ws.Close()
}()
c.ws.SetReadLimit(maxMessageSize)
c.ws.SetReadDeadline(time.Now().Add(readWait))
2015-07-06 13:12:03 +00:00
c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(readWait)); return nil })
2013-09-10 10:38:40 +00:00
for {
op, r, err := c.ws.NextReader()
if err != nil {
break
}
switch op {
2014-06-13 22:21:26 +00:00
case websocket.TextMessage:
2013-09-10 10:38:40 +00:00
message, err := ioutil.ReadAll(r)
if err != nil {
break
}
h.broadcast <- []byte(c.username + "_" + time.Now().Format("15:04:05") + ":" + string(message))
}
}
}
// write writes a message with the given opCode and payload.
func (c *connection) write(opCode int, payload []byte) error {
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
return c.ws.WriteMessage(opCode, payload)
}
// writePump pumps messages from the hub to the websocket connection.
func (c *connection) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.ws.Close()
}()
for {
select {
case message, ok := <-c.send:
if !ok {
2014-06-13 22:21:26 +00:00
c.write(websocket.CloseMessage, []byte{})
2013-09-10 10:38:40 +00:00
return
}
2014-06-13 22:21:26 +00:00
if err := c.write(websocket.TextMessage, message); err != nil {
2013-09-10 10:38:40 +00:00
return
}
case <-ticker.C:
2014-06-13 22:21:26 +00:00
if err := c.write(websocket.PingMessage, []byte{}); err != nil {
2013-09-10 10:38:40 +00:00
return
}
}
}
}
type hub struct {
// Registered connections.
connections map[*connection]bool
// Inbound messages from the connections.
broadcast chan []byte
// Register requests from the connections.
register chan *connection
// Unregister requests from connections.
unregister chan *connection
}
var h = &hub{
broadcast: make(chan []byte, maxMessageSize),
register: make(chan *connection, 1),
unregister: make(chan *connection, 1),
connections: make(map[*connection]bool),
}
func (h *hub) run() {
for {
select {
case c := <-h.register:
h.connections[c] = true
case c := <-h.unregister:
delete(h.connections, c)
close(c.send)
case m := <-h.broadcast:
for c := range h.connections {
select {
case c.send <- m:
default:
close(c.send)
delete(h.connections, c)
}
}
}
}
}
type WSController struct {
beego.Controller
}
2014-06-13 22:21:26 +00:00
var upgrader = websocket.Upgrader{
2014-10-31 07:48:57 +00:00
ReadBufferSize: 1024,
WriteBufferSize: 1024,
2014-06-13 22:21:26 +00:00
}
2014-11-05 14:40:31 +00:00
func (w *WSController) Get() {
ws, err := upgrader.Upgrade(w.Ctx.ResponseWriter, w.Ctx.Request, nil)
2013-09-10 10:38:40 +00:00
if _, ok := err.(websocket.HandshakeError); ok {
2014-11-05 14:40:31 +00:00
http.Error(w.Ctx.ResponseWriter, "Not a websocket handshake", 400)
2013-09-10 10:38:40 +00:00
return
} else if err != nil {
return
}
c := &connection{send: make(chan []byte, 256), ws: ws, username: randomString(10)}
h.register <- c
go c.writePump()
c.readPump()
}
func randomString(l int) string {
bytes := make([]byte, l)
for i := 0; i < l; i++ {
bytes[i] = byte(randInt(65, 90))
}
return string(bytes)
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}