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


Golang Conn.WriteMessage方法代码示例

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


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

示例1: write

func write(ws *websocket.Conn, mt int, payload []byte) error {
	if ws == nil {
		return errors.New("no web socket connection: ws")
	}
	ws.SetWriteDeadline(time.Now().Add(writeWait))
	return ws.WriteMessage(mt, payload)
}
开发者ID:benjamingram,项目名称:stem,代码行数:7,代码来源:websocket.go

示例2: 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

示例3: 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

示例4: activateWSProxySubject

func (np *NatsProxy) activateWSProxySubject(conn *websocket.Conn, wsID string) {
	np.addToWSMapper(conn, wsID)
	np.conn.Subscribe("WS_OUT"+wsID, func(m *nats.Msg) {
		err := conn.WriteMessage(websocket.TextMessage, m.Data)
		if err != nil {
			log.Println("Error writing a message", err)
		}
	})
	go func() {
		for {
			if _, p, err := conn.ReadMessage(); err == nil {
				np.conn.Publish("WS_IN"+wsID, p)
			} else {
				np.removeFromWSMapper(conn, wsID)
				conn.Close()
				// If websocket is closed normally RFC6455
				// code 1000, then no error logged
				if !websocket.IsCloseError(err, websocket.CloseNormalClosure) {
					logWebsocketError(wsID, err)
				}
				break
			}
		}
	}()
}
开发者ID:sohlich,项目名称:nats-proxy,代码行数:25,代码来源:proxy.go

示例5: WebsocketSendStream

func WebsocketSendStream(conn *websocket.Conn, r io.Reader) chan bool {
	ch := make(chan bool)

	go func(conn *websocket.Conn, r io.Reader) {
		in := ReaderToChannel(r)
		for {
			buf, ok := <-in
			if !ok {
				break
			}

			w, err := conn.NextWriter(websocket.BinaryMessage)
			if err != nil {
				Debugf("got error getting next writer %s", err)
				break
			}

			_, err = w.Write(buf)
			w.Close()
			if err != nil {
				Debugf("got err writing %s", err)
				break
			}
		}
		closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
		conn.WriteMessage(websocket.CloseMessage, closeMsg)
		ch <- true
	}(conn, r)

	return ch
}
开发者ID:dvbportal,项目名称:osx-lxd,代码行数:31,代码来源:util.go

示例6: writer

func writer(ws *websocket.Conn) {
	pingTicker := time.NewTicker(pingPeriod)
	nodesTicker := time.NewTicker(nodesPeriod)
	defer func() {
		pingTicker.Stop()
		nodesTicker.Stop()
		ws.Close()
	}()
	for {
		select {
		case <-nodesTicker.C:

			p := []byte(fmt.Sprintf("%v", nodesH))

			if p != nil {
				ws.SetWriteDeadline(time.Now().Add(writeWait))
				if err := ws.WriteMessage(websocket.TextMessage, p); err != nil {
					return
				}
			}
		case <-pingTicker.C:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}
开发者ID:mehulsbhatt,项目名称:honeybee,代码行数:28,代码来源:http_server.go

示例7: primeRequestMainLoop

func primeRequestMainLoop(ws *websocket.Conn) {
	msgType, msg, err := ws.ReadMessage()
	for ; err == nil && msgType == websocket.TextMessage; msgType, msg, err = ws.ReadMessage() {
		req := string(msg)
		fields := strings.Fields(req)
		if len(fields) == 0 {
			err = ws.WriteMessage(websocket.TextMessage, []byte(warnArgCount))
		} else {
			method := strings.ToUpper(fields[0])
			switch method {
			case "?":
				err = ws.WriteMessage(msgType, []byte(helpMsg))
			case "TEST":
				if len(fields) > 1 {
					err = OnTest(ws, fields[1:])
				} else {
					err = ws.WriteMessage(msgType, []byte("ERROR: nothing to test"))
				}
			case "LIST":
				err = OnList(ws, fields[1:])
			case "EXIT":
				fallthrough
			case "QUIT":
				fallthrough
			case "CLOSE":
				fmt.Fprintln(os.Stderr, "INFO: Closing Websocket...")
				break
			default:
				err = ws.WriteMessage(msgType, []byte(errorUnknownCmd))
			}
		}
		err = ws.WriteMessage(websocket.TextMessage, []byte(eotMsg))
	}
}
开发者ID:vachu,项目名称:prime,代码行数:34,代码来源:prime_wss.go

示例8: 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

示例9: WebsocketSendStream

func WebsocketSendStream(conn *websocket.Conn, r io.Reader) chan bool {
	ch := make(chan bool)

	if r == nil {
		close(ch)
		return ch
	}

	go func(conn *websocket.Conn, r io.Reader) {
		in := ReaderToChannel(r)
		for {
			buf, ok := <-in
			if !ok {
				break
			}

			w, err := conn.NextWriter(websocket.BinaryMessage)
			if err != nil {
				Debugf("Got error getting next writer %s", err)
				break
			}

			_, err = w.Write(buf)
			w.Close()
			if err != nil {
				Debugf("Got err writing %s", err)
				break
			}
		}
		conn.WriteMessage(websocket.TextMessage, []byte{})
		ch <- true
	}(conn, r)

	return ch
}
开发者ID:czl349095941,项目名称:lxd,代码行数:35,代码来源:network.go

示例10: sendCloseMessage

func sendCloseMessage(t *testing.T, ws *websocket.Conn) {
	err := ws.WriteMessage(websocket.CloseMessage, []byte{})

	assert.Nil(t, err, "ws: %v", err)

	wait(10)
}
开发者ID:fredrikzkl,项目名称:gamesystem,代码行数:7,代码来源:hub_test.go

示例11: 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

示例12: sendGameStateToConnection

// sendGameStateToConnection broadcasts the current gameState as JSON to all players
// within a connectionPair
func sendGameStateToConnection(wsConn *websocket.Conn, c *connection) {
	err := wsConn.WriteMessage(websocket.TextMessage, c.cp.gs.gameStateToJSON())
	//removing connection if updating gameState fails
	if err != nil {
		c.cp.removeConnection(c)
	}
}
开发者ID:riscie,项目名称:websocket-tic-tac-toe,代码行数:9,代码来源:connection.go

示例13: runInit

func runInit(c *websocket.Conn) {
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	initPath := path.Join(dir, "init.cmd")
	if _, err := os.Stat(initPath); err == nil {
		file, err := os.Open(initPath)
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()

		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			line := strings.TrimSpace(scanner.Text())
			log.Println(line)
			if line != "" && !strings.HasPrefix(line, "#") {
				fmt.Println("<<", line)
				c.WriteMessage(websocket.TextMessage, []byte(line))
			}
		}

		if err := scanner.Err(); err != nil {
			log.Fatal(err)
		}
	}
}
开发者ID:averrin,项目名称:darklin-game,代码行数:25,代码来源:main.go

示例14: writer

func (ws *WebSocker) writer(conn *websocket.Conn, user string, tmpl *template.Template) {
	pingTicker := time.NewTicker(pingPeriod)
	chl, chq := notifier.listen(user)
	ws.log.Println(user, "connected")
	defer func() {
		pingTicker.Stop()
		conn.Close()
		close(chq)
		ws.log.Println(user, "disconnected")
	}()
	for {
		var buf bytes.Buffer
		select {
		case p := <-chl:
			conn.SetWriteDeadline(time.Now().Add(writeWait))
			buf.Reset()
			if err := tmpl.Execute(&buf, p); err != nil {
				ws.log.Println(err)
				return
			}
			if err := conn.WriteMessage(websocket.TextMessage, buf.Bytes()); err != nil {
				return
			}
			ws.log.Println("notified:", user)
		case <-pingTicker.C:
			conn.SetWriteDeadline(time.Now().Add(writeWait))
			if err := conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				ws.log.Println("ping:", err)
				return
			}
		}
	}
}
开发者ID:mehulsbhatt,项目名称:web-ftp-upload,代码行数:33,代码来源:websocket.go

示例15: pipe_to_ws

func pipe_to_ws(netConn net.Conn, wsConn *websocket.Conn, protocolType int, stopChan chan int) {
	for {
		select {
		case <-stopChan:
			return
		default:
			{
				data := make([]byte, BUFFER_SIZE)
				n, err := netConn.Read(data)
				if err != nil {
					stopChan <- 1
					return
				}

				if protocolType == websocket.BinaryMessage {
					err = wsConn.WriteMessage(protocolType, data[:n])
					if err != nil {
						stopChan <- 1
						return
					}
				} else if protocolType == websocket.TextMessage {
					encodedData := []byte(base64.StdEncoding.EncodeToString(data[:n]))
					err = wsConn.WriteMessage(protocolType, encodedData)
					if err != nil {
						stopChan <- 1
						return
					}
				}
			}
		}
	}
}
开发者ID:liu-junyong,项目名称:tcp2ws-go,代码行数:32,代码来源:tcp2ws.go


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