本文整理汇总了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)
}
示例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
}
}
}
}
示例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
}
示例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
}
}
}()
}
示例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
}
示例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
}
}
}
}
示例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))
}
}
示例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
}
示例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
}
示例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)
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
}
示例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
}
}
}
}
示例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
}
}
}
}
}
}