当前位置: 首页>>代码示例>>Golang>>正文


Golang websocket.Conn类代码示例

本文整理汇总了Golang中github.com/gorilla/websocket.Conn的典型用法代码示例。如果您正苦于以下问题:Golang Conn类的具体用法?Golang Conn怎么用?Golang Conn使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Conn类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: streamStatus

func streamStatus(sock *websocket.Conn) {
	installed := installedPacks()
	filteredInstalled := []shared.Pack{}
	available := availablePacks()

loopinstalled:
	for _, ip := range installed {
		for ai, ap := range available {
			if ip.Installing && ip.File == ap.File {
				available[ai].Installing = true
				continue loopinstalled
			}
		}
		filteredInstalled = append(filteredInstalled, ip)
	}

	info := StatusInfo{
		Packs: PackInfo{
			Installed: filteredInstalled,
			Available: available,
		},
		Version: global.buildVersion,
	}

	err := sock.WriteJSON(controlResponse{Typ: "StatusResponse", Data: info})
	if err != nil {
		log.Printf("Error while writing status info: %v\n", err)
		return
	}
}
开发者ID:fgeller,项目名称:rad,代码行数:30,代码来源:server.go

示例2: loadLatestSales

func loadLatestSales(websocketConnection *websocket.Conn) {
	results, err := r.Table("analytics").Filter(M{
		"type": "sale",
	}).OrderBy(
		r.Desc(r.Row.Field("data").Field("date")),
	).Limit(10).Map(func(row r.Term) interface{} {
		return row.Field("data")
	}).Run(rethinkSession)
	if err != nil {
		log.Printf("error loadLatestSales: %q", err)
	}
	defer results.Close()

	var latestSales []interface{}
	err = results.All(&latestSales)
	if err != nil {
		log.Println(err)
		return
	}

	log.Printf("sending latest %d sales\n", len(latestSales))

	socketOutgoingMessage := &SocketOutgoingMessage{
		Function: "loadLatestSales",
		Data: M{
			"type": "sale",
			"data": latestSales,
		},
	}

	err = websocketConnection.WriteJSON(socketOutgoingMessage)
	if err != nil {
		log.Println(err)
	}
}
开发者ID:gagliardetto,项目名称:RethinkDB-Golang-dashboard,代码行数:35,代码来源:analytics.go

示例3: jionToChatRoom

func jionToChatRoom(uname string, ws *websocket.Conn) {

	// Join chat room.
	Join(uname, ws)
	defer Leave(uname)

	// Message receive loop.
	for {
		_, p, err := ws.ReadMessage()
		if err != nil {
			return
		}
		//=======deal with chat====
		// js, err := simplejson.NewJson(p)
		// if err != nil {
		// 	panic(err.Error())
		// }
		chat := new(models.ChatBean)
		json.Unmarshal(p, chat)

		//=====================
		if chat.Type == 1 || len(chat.To) > 0 {
			publish <- newEvent(models.EVENT_CHAT, uname, string(p))
		} else {
			publish <- newEvent(models.EVENT_MESSAGE, uname, string(p))
		}

	}
}
开发者ID:ray0807,项目名称:goAPI,代码行数:29,代码来源:websocket.go

示例4: wsHeartbeat

// NOTE :: When a guild voice server changes how do we shut this down
// properly, so a new connection can be setup without fuss?
//
// wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
// is still connected.  If you do not send these heartbeats Discord will
// disconnect the websocket connection after a few seconds.
func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {

	if close == nil || wsConn == nil {
		return
	}

	var err error
	ticker := time.NewTicker(i * time.Millisecond)
	for {
		v.log(LogDebug, "sending heartbeat packet")
		v.wsMutex.Lock()
		err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
		v.wsMutex.Unlock()
		if err != nil {
			v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err)
			return
		}

		select {
		case <-ticker.C:
			// continue loop and send heartbeat
		case <-close:
			return
		}
	}
}
开发者ID:42wim,项目名称:matterbridge,代码行数:32,代码来源:voice.go

示例5: newWSConn

func newWSConn(conn *websocket.Conn, pendingWriteNum int) *WSConn {
	wsConn := new(WSConn)
	wsConn.conn = conn
	wsConn.writeChan = make(chan []byte, pendingWriteNum)

	go func() {
		for b := range wsConn.writeChan {
			if b == nil {
				break
			}

			err := conn.WriteMessage(websocket.BinaryMessage, b)
			if err != nil {
				break
			}
		}

		conn.Close()
		wsConn.Lock()
		wsConn.closeFlag = true
		wsConn.Unlock()
	}()

	return wsConn
}
开发者ID:haoqoo,项目名称:leaf,代码行数:25,代码来源:ws_conn.go

示例6: connectToAgent

func connectToAgent(timeout int, onReady func(*websocket.Conn)) (*websocket.Conn, error) {
	var ws *websocket.Conn
	var err error

	t := 0
	for {
		if t > timeout {
			return nil, errors.New("Connection to Agent : timeout reached")
		}

		ws, err = newClient()
		if err == nil {
			break
		}
		time.Sleep(1 * time.Second)
		t++
	}

	ready := false
	h := func(message string) error {
		err := ws.WriteControl(websocket.PongMessage, []byte(message), time.Now().Add(time.Second))
		if err != nil {
			return err
		}
		if !ready {
			ready = true
			onReady(ws)
		}
		return nil
	}
	ws.SetPingHandler(h)

	return ws, nil
}
开发者ID:mestery,项目名称:skydive,代码行数:34,代码来源:topology_test.go

示例7: createPlayer

func createPlayer(conn *websocket.Conn) {
	message, _ := json.Marshal(&Message{Title: "createPlayer", Data: connections.m[conn]})

	if err := conn.WriteMessage(websocket.TextMessage, message); err != nil {
		closeConnection(conn)
	}
}
开发者ID:PiusNyakoojo,项目名称:golang_multiplayer_template,代码行数:7,代码来源:server.go

示例8: listenForIncomingData

func (w *WebsocketController) listenForIncomingData(connection *websocket.Conn, client *WebsocketClient, disconnect chan bool) {
	for {
		mt, message, err := connection.ReadMessage()

		if mt == websocket.CloseMessage {
			disconnect <- true
		}
		if _, ok := err.(*websocket.CloseError); ok {
			disconnect <- true
		}

		if err != nil {
			w.logger.Println("warning: read message error:", err)
			continue
		}
		if mt != websocket.TextMessage && mt != websocket.CloseMessage {
			w.logger.Println("warning: recieved unsupported message: ", mt, message)
			continue
		}

		if mt == websocket.TextMessage {
			w.Received() <- ReceivedData{client, message}
		}
	}
}
开发者ID:roblaszczak,项目名称:simple-go-chat,代码行数:25,代码来源:controller.go

示例9: handleWs

func handleWs(s Service, ws *websocket.Conn, subs map[uint32]*wsSub, slock *sync.Mutex) error {
	ch := make(chan []byte)
	defer close(ch)

	go func() {
		for {
			v, ok := <-ch
			if !ok {
				break
			}

			if err := ws.WriteMessage(websocket.BinaryMessage, v); err != nil {
				fmt.Printf("ws.WriteMessage: %#v\n", err)
				break
			}
		}
	}()

	for {
		mt, msg, err := ws.ReadMessage()
		if err != nil {
			fmt.Printf("ws.ReadMessage: %#v\n", err)
			break
		}

		if mt != websocket.BinaryMessage {
			continue
		}

		if err := iter(ch, msg, s, subs, slock); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:Monnoroch,项目名称:golfstream,代码行数:35,代码来源:handler.go

示例10: streamWebsocket

func (w *WebsocketServer) streamWebsocket(websocketSink *websocket.WebsocketSink, websocketConnection *gorilla.Conn, register func(sinks.Sink) bool, unregister func(sinks.Sink)) {
	register(websocketSink)
	defer unregister(websocketSink)

	go websocketConnection.ReadMessage()
	server.NewKeepAlive(websocketConnection, w.keepAliveInterval).Run()
}
开发者ID:yingkitw,项目名称:loggregator,代码行数:7,代码来源:websocket_server.go

示例11: writer

// writer runs in a goroutine for each connected WS client. It emits all message returned by the observer.
func writer(ws *websocket.Conn, a *ApiHandlers) {
	pingTicker := time.NewTicker(pingPeriod)
	s := a.getDBSubscriber()
	jww.INFO.Println("Opened WebSocket connection.")
	defer func(is *subscriber) {
		jww.INFO.Println("Closing WebSocket connection.")
		is.quitChan <- true
		pingTicker.Stop()
		ws.Close()
	}(s)

	for {
		select {
		case msg := <-s.bufChan:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteJSON(msg); err != nil {
				return
			}
		case <-pingTicker.C:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}
开发者ID:ValleyCamp,项目名称:WeatherMoss,代码行数:27,代码来源:wshandler.go

示例12: registerSocket

func (app *App) registerSocket(ws *websocket.Conn, hub *Hub, toHub *Hub) {
	defer hub.RemoveMember(ws)
	hub.AddMember(ws)

	app.KeepAlive()

	from := toHub.FromLabel
	to := toHub.ToLabel
	appname := app.Name

	for {
		mtype, p, err := ws.ReadMessage()
		if err != nil {
			log.Printf("%s: Connection (%s): %s", app.Name, from, err)
			break
		}

		msg := &AppMessage{Data: p,
			Mtype: mtype,
			Id:    int(atomic.AddInt32(&msgcnt, 1)),
			To:    toHub}
		log.Printf("%s: QUEUE [%d] %s -> %s (of %d) [%s]", appname, msg.Id, from, to, len(hub.Members), string(msg.Data))
		app.Channel <- msg
	}
}
开发者ID:jondot,项目名称:castbox,代码行数:25,代码来源:app.go

示例13: PushMsg

func PushMsg(ws *websocket.Conn, WSWriter chan []uint8) {

	defer ws.Close()

	for {
		msg := <-WSWriter

		if msg == nil {
			continue
		}

		// write message to client
		if err := ws.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
			log.Println("[ErrorInfo]", err.Error())
			break
		}

		if string(msg) == "bye" {
			break
		}
	}

	endChan <- true

}
开发者ID:pombredanne,项目名称:generator-1,代码行数:25,代码来源:log.go

示例14: streamResults

func streamResults(sock *websocket.Conn, params searchParams, limit int) {
	start := time.Now()
	count := 0
	results := make(chan searchResult)
	control := make(chan struct{}, 1)

	go find(results, control, params)
	for {
		res, ok := <-results
		if !ok {
			log.Printf("Finished request in %v\n", time.Since(start))
			return
		}

		count++
		log.Printf("Found result #%v after %v\n", count, time.Since(start))

		err := sock.WriteJSON(res)
		if err != nil {
			log.Printf("Error while writing result: %v\n", err)
			control <- struct{}{}
			return
		}

		if count >= limit {
			log.Printf("Finished request after hitting limit in %v\n", time.Since(start))
			control <- struct{}{}
			return
		}
	}
}
开发者ID:fgeller,项目名称:rad,代码行数:31,代码来源:server.go

示例15: wsSend

func wsSend(con *websocket.Conn, msgSend chan WSMsg, done, readDone, stopWS chan int) {
	defer fmt.Println("wsSend: goroutine stopped")
	seq := 1
	for {
		select {
		case <-stopWS:
			stopSend(con, done)
			return
		case <-readDone:
			stopSend(con, done)
			return
		case nextMsg, ok := <-msgSend:
			if ok {
				//send the message on the channel to the connection
				nextMsg.Seq = seq
				seq++
				fmt.Println("wsSend: sending msg", nextMsg.Type)
				j, _ := json.Marshal(nextMsg)
				fmt.Printf("wsSend: msg sent: `%s`\n", j)
				if err := con.WriteJSON(&nextMsg); err != nil {
					fmt.Println("wsSend:", err)
				}
			}
		}
	}
}
开发者ID:uniquoooo,项目名称:discordapi,代码行数:26,代码来源:ws.go


注:本文中的github.com/gorilla/websocket.Conn类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。