本文整理匯總了Golang中github.com/gorilla/websocket.Conn.ReadMessage方法的典型用法代碼示例。如果您正苦於以下問題:Golang Conn.ReadMessage方法的具體用法?Golang Conn.ReadMessage怎麽用?Golang Conn.ReadMessage使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gorilla/websocket.Conn
的用法示例。
在下文中一共展示了Conn.ReadMessage方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: 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}
}
}
}
示例2: run
func (self *remoteService) run(ws *websocket.Conn) error {
for {
mt, msg, err := ws.ReadMessage()
if err != nil {
fmt.Printf("remoteService.run: %#v\n", err)
break
}
if mt != websocket.BinaryMessage {
continue
}
cmd := cmdResult{}
if err := json.NewDecoder(bytes.NewReader(msg)).Decode(&cmd); err != nil {
return err
}
if cmd.Id == nil {
if err := self.handleEvent(cmd.Back, cmd.Sid, stream.Event([]byte(cmd.Data))); err != nil {
return err
}
} else {
if err := self.handleCmdRes(*cmd.Id, cmd.Data); err != nil {
return err
}
}
}
return nil
}
示例3: pipeLogs
func (r *RancherService) pipeLogs(container *rancherClient.Container, conn *websocket.Conn) {
defer conn.Close()
log_name := strings.TrimPrefix(container.Name, r.context.ProjectName+"_")
logger := r.context.LoggerFactory.Create(log_name)
for {
messageType, bytes, err := conn.ReadMessage()
if messageType != websocket.TextMessage {
continue
}
if err == io.EOF {
return
} else if err != nil {
logrus.Errorf("Failed to read log: %v", err)
return
}
if len(bytes) <= 3 {
continue
}
if bytes[len(bytes)-1] != '\n' {
bytes = append(bytes, '\n')
}
message := bytes[3:]
if "01" == string(bytes[:2]) {
logger.Out(message)
} else {
logger.Err(message)
}
}
}
示例4: 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()
}
示例5: 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
}
}
}()
}
示例6: 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))
}
}
}
示例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: pipe_to_net
func pipe_to_net(netConn net.Conn, wsConn *websocket.Conn, protocolType int, stopChan chan int) {
for {
select {
case <-stopChan:
return
default:
{
_, p, err := wsConn.ReadMessage()
if err != nil {
stopChan <- 1
return
}
if protocolType == websocket.BinaryMessage {
_, err = netConn.Write(p)
if err != nil {
stopChan <- 1
return
}
} else if protocolType == websocket.TextMessage {
data := make([]byte, base64.StdEncoding.DecodedLen(len(p)))
n, err := base64.StdEncoding.Decode(data, p)
if err != nil {
stopChan <- 1
return
}
_, err = netConn.Write(data[:n])
if err != nil {
stopChan <- 1
return
}
}
}
}
}
}
示例9: readMessages
func readMessages(ws *websocket.Conn, rc chan<- error, handler Handler) (e error) {
defer func() {
rc <- e
}()
for {
_, msg, err := ws.ReadMessage()
if err != nil {
return fmt.Errorf("Error reading from websocket: %s", err)
}
var event model.WatchEvent
err = json.Unmarshal(msg, &event)
if err != nil {
return fmt.Errorf("Error parsing event: %s", err)
}
log.Infof("Received event: [%s]", msg)
err = handler.Handle(event)
if err != nil {
return fmt.Errorf("Error handling event: %s", err)
}
}
}
示例10: checkResponse
func checkResponse(checkFor map[string]string, ws *websocket.Conn, c *check.C) string {
for count := 0; count < 20; count++ {
_, m, err := ws.ReadMessage()
if err != nil {
// ws closed
if len(checkFor) != 0 {
c.Fatal("Didn't find all keys before ws was closed: ", checkFor)
}
return ""
}
dst := make([]byte, base64.StdEncoding.EncodedLen(len(m)))
_, err = base64.StdEncoding.Decode(dst, m)
if err != nil {
c.Fatal(err)
}
msg := string(dst)
for k, _ := range checkFor {
if strings.Contains(msg, k) {
delete(checkFor, k)
}
}
if len(checkFor) == 0 {
return msg
}
}
if len(checkFor) != 0 {
c.Fatal("Didn't find: ", checkFor)
}
return ""
}
示例11: datawsHandler
func datawsHandler(w http.ResponseWriter, r *http.Request) {
var websocket *ws.Conn
var upgradeerr error
websocket, upgradeerr = upgrader.Upgrade(w, r, nil)
if upgradeerr != nil {
w.Write([]byte(fmt.Sprintf("Could not upgrade HTTP connection to WebSocket: %v\n", upgradeerr)))
return
}
cw := ConnWrapper{
Writing: &sync.Mutex{},
Conn: websocket,
}
websocket.SetReadLimit(MAX_REQSIZE)
for {
_, payload, err := websocket.ReadMessage()
if err != nil {
return // Most likely the connection was closed or the message was too big
}
uuidBytes, startTime, endTime, pw, token, echoTag, success := parseDataRequest(string(payload), &cw)
if success {
var loginsession *LoginSession
if token != "" {
loginsession = validateToken(token)
if loginsession == nil {
w.Write([]byte(ERROR_INVALID_TOKEN))
return
}
}
if hasPermission(loginsession, uuidBytes) {
dr.MakeDataRequest(uuidBytes, startTime, endTime, uint8(pw), &cw)
} else {
cw.GetWriter().Write([]byte("[]"))
}
}
if cw.CurrWriter != nil {
cw.CurrWriter.Close()
}
writer, err := websocket.NextWriter(ws.TextMessage)
if err != nil {
fmt.Println("Could not echo tag to client")
}
if cw.CurrWriter != nil {
_, err = writer.Write([]byte(echoTag))
if err != nil {
fmt.Println("Could not echo tag to client")
}
writer.Close()
}
cw.Writing.Unlock()
}
}
示例12: proxyConnectionTo
func (handler *handler) proxyConnectionTo(server *websocket.Conn) {
handler.logger.Debugf("Output Proxy: Starting to listen to server %v", server.RemoteAddr().String())
var logMessage []byte
defer server.Close()
count := 0
for {
_, data, err := server.ReadMessage()
if err != nil {
handler.logger.Errorf("Output Proxy: Error reading from the server - %v - %v", err, server.RemoteAddr().String())
handler.Done()
return
}
handler.logger.Debugf("Output Proxy: Got message from server %v bytes", len(logMessage))
count++
err = handler.writeMessage(data)
if err != nil {
handler.logger.Errorf("Output Proxy: Error writing to client websocket - %v", err)
return
}
}
}
示例13: socketRead
func socketRead(c *websocket.Conn) {
for {
_, r, err := c.ReadMessage()
internal.Check(err)
fmt.Print(color(string(r)))
}
}
示例14: loop
func (bot *Bot) loop(conn *websocket.Conn) bool {
defer conn.Close()
for {
messageType, bytes, err := conn.ReadMessage()
if err != nil {
// ReadMessage returns an error if the connection is closed
return false
}
if messageType == websocket.BinaryMessage {
continue // ignore binary messages
}
event, err := unpackJSON(bytes)
if err != nil {
log.WithFields(log.Fields{
"raw bytes": bytes,
"error": err,
}).Warn("message could not be unpacked")
continue
}
log.WithFields(log.Fields{
"event": event,
}).Info("received event")
eventType, ok := event["type"]
if ok && eventType.(string) == "team_migration_started" {
return true
}
wrappers := bot.handle(event)
closeConnection := sendResponses(wrappers, conn)
if closeConnection {
return false
}
}
}
示例15: wsReadPump
func (this *subServer) wsReadPump(clientGone chan struct{}, ws *websocket.Conn) {
ws.SetReadLimit(this.wsReadLimit)
ws.SetReadDeadline(time.Now().Add(this.wsPongWait))
ws.SetPongHandler(func(string) error {
ws.SetReadDeadline(time.Now().Add(this.wsPongWait))
return nil
})
// if kateway shutdown while there are open ws conns, the shutdown will
// wait 1m: this.subServer.wsPongWait
for {
_, message, err := ws.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
log.Warn("%s: %v", ws.RemoteAddr(), err)
} else {
log.Debug("%s: %v", ws.RemoteAddr(), err)
}
close(clientGone)
break
}
log.Debug("ws[%s] read: %s", ws.RemoteAddr(), string(message))
}
}