• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang websocket.IsUnexpectedCloseError函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: readPump

// readPump pumps messages from the websocket connection to the hub.
func (c *Conn) readPump() {
	defer func() {
		hub.unregister <- c
		c.ws.Close()
	}()
	c.ws.SetReadLimit(maxMessageSize)
	c.ws.SetReadDeadline(time.Now().Add(pongWait))
	c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.ws.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v", err)
			}
			break
		}
		message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))

		msg := &Message{}
		err = json.Unmarshal(message, msg)
		bo := strings.Split(string(message), ",")
		target := hub.connections[bo[0]]
		if target != nil {
			target.send <- []byte(bo[1])
		}

		if err != nil {
			// byte message
			continue
		}
		//service.SendMessage(msg, string(message))
		//		hub.broadcast <- message
	}
}
开发者ID:cs6402,项目名称:goose,代码行数:35,代码来源:conn.go


示例2: writePump

// writePump pumps messages from the toplevel to the websocket connection.
func (c *Client) writePump() {
	defer func() {
		c.conn.Close()
		c.top.terminate()
	}()

	buf := make([]byte, 4*1024)
	for {
		n, err := c.top.stdout.Read(buf)
		//		log.Printf("Read %s", buf[:n])
		if n > 0 {
			err := c.conn.WriteMessage(websocket.TextMessage, buf[:n])
			if err != nil {
				if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway,
					websocket.CloseNoStatusReceived) {
					log.Printf("Writepump websocket error: %s", err)
				}

				break
			}
		} else {
			if err != nil {
				if err != io.EOF {
					log.Printf("Writepump Unexpected error while reading STDOUT from process: %s", err)
				} else {
					log.Printf("Writepump Process STDOUT closed: %s", err)
				}
				break
			}
		}
	}
}
开发者ID:kfl,项目名称:trymosml,代码行数:33,代码来源:client.go


示例3: handleOutput

func (h *Hijacker) handleOutput(conn *websocket.Conn, pio ProcessIO) int {
	var exitStatus int
	for {
		var output atc.HijackOutput
		err := conn.ReadJSON(&output)
		if err != nil {
			if !websocket.IsCloseError(err) && !websocket.IsUnexpectedCloseError(err) {
				fmt.Println(err)
			}
			break
		}

		if output.ExitStatus != nil {
			exitStatus = *output.ExitStatus
		} else if len(output.Error) > 0 {
			fmt.Fprintf(os.Stderr, "%s\n", ansi.Color(output.Error, "red+b"))
			exitStatus = 255
		} else if len(output.Stdout) > 0 {
			pio.Out.Write(output.Stdout)
		} else if len(output.Stderr) > 0 {
			pio.Err.Write(output.Stderr)
		}
	}

	return exitStatus
}
开发者ID:ArthurHlt,项目名称:fly,代码行数:26,代码来源:hijacker.go


示例4: readPump

// 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(pongWait))
	c.ws.SetPongHandler(func(string) error {
		c.ws.SetReadDeadline(time.Now().Add(pongWait))
		return nil
	})

	for {
		_, message, err := c.ws.ReadMessage()
		fmt.Println(string(message))

		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v", err)
			}
			break
		}
	}
}
开发者ID:pselibas,项目名称:semaphore,代码行数:26,代码来源:handler.go


示例5: handleConnectionError

func handleConnectionError(connection *Connection, err error) {
	if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
		log.Printf("Unexpected error from connection: %q", err)
	}

	hub.Unregister(connection)
}
开发者ID:frankdejonge,项目名称:golang-websocket-example,代码行数:7,代码来源:connection.go


示例6: connectionHandler

//Callback function that is called for new connection.
func connectionHandler(w http.ResponseWriter, r *http.Request, server *WServer) {
	conn, err := gorillaUpgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("connectionHandler: gorillaUpgrader: ", err)
		return
	}
	defer func() {
		//dev
		log.Println("Connection close: ", conn.RemoteAddr())
		conn.Close()
	}()

	//dev
	log.Println("New connection: ", conn.RemoteAddr())

	client := Client{server.OnMessage, conn}
	defer server.OnClose(&client)
	for {
		messageType, r, err := conn.NextReader()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Println("Connection handler: ", err)
			}
			return
		}
		new_msg := &Message{&r, messageType}
		client.onmessage(new_msg, &client)
	}
}
开发者ID:angrypie,项目名称:remote-desktop,代码行数:30,代码来源:wserver.go


示例7: readPump

// readPump pumps messages from the websocket connection to the hub.
func (c *Client) readPump() {
	defer func() {
		c.hub.unregister <- c
		c.conn.Close()
	}()
	c.conn.SetReadLimit(maxMessageSize)
	c.conn.SetReadDeadline(time.Now().Add(pongWait))
	c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v", err)
			} else {
				log.Printf("Client disconnected")
			}
			break
		}
		if c.hub.read {
			c.hub.ReadBuffer.Lock()
			c.hub.ReadBuffer.Messages = append(c.hub.ReadBuffer.Messages, &message)
			c.hub.ReadBuffer.Unlock()
		}
	}
}
开发者ID:emccode,项目名称:mars-challenge,代码行数:26,代码来源:websocket.go


示例8: readPump

// readPump pumps messages from the websocket connection to the hub.
func (u *User) readPump() {
	defer func() {
		u.g.unregister <- u
		u.ws.Close()
	}()

	u.ws.SetReadLimit(maxMessageSize)
	u.ws.SetReadDeadline(time.Now().Add(pongWait))
	u.ws.SetPongHandler(func(string) error {
		u.ws.SetReadDeadline(time.Now().Add(pongWait))
		return nil
	})

	for {
		_, message, err := u.ws.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				// TODO: do something??
			}

			u.Log.Error(err.Error())

			return
		}

		u.Log.WithField("content", string(message)).Debug("new message")

		c := NewCommand(u, string(message))

		u.g.commands <- c
	}
}
开发者ID:wyattjoh,项目名称:spacegophers,代码行数:33,代码来源:user.go


示例9: 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))
	}
}
开发者ID:funkygao,项目名称:gafka,代码行数:26,代码来源:handler_sub_ws.go


示例10: ExampleIsUnexpectedCloseError

// The websocket.IsUnexpectedCloseError function is useful for identifying
// application and protocol errors.
//
// This server application works with a client application running in the
// browser. The client application does not explicitly close the websocket. The
// only expected close message from the client has the code
// websocket.CloseGoingAway. All other other close messages are likely the
// result of an application or protocol error and are logged to aid debugging.
func ExampleIsUnexpectedCloseError(err error, c *websocket.Conn, req *http.Request) {
	for {
		messageType, p, err := c.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v, user-agent: %v", err, req.Header.Get("User-Agent"))
			}
			return
		}
		processMesage(messageType, p)
	}
}
开发者ID:CNDonny,项目名称:scope,代码行数:20,代码来源:example_test.go


示例11: readPump

// readPump pumps messages from the websocket connection to the hub.
func (s *subscription) readPump() {
	defer func() {
		Hub.unregister <- s
		s.conn.ws.Close()
	}()
	s.conn.ws.SetReadLimit(maxMessageSize)
	s.conn.ws.SetReadDeadline(time.Now().Add(pongWait))
	s.conn.ws.SetPongHandler(func(string) error {
		log.Println("[DEBUG] In pong handler", s.conn.username)
		s.conn.ws.SetReadDeadline(time.Now().Add(pongWait))
		return nil
	})
	for {
		_, message, err := s.conn.ws.ReadMessage()
		if err != nil {

			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v", err)
			}
			log.Printf("error: %v", err)
			break
		}
		// Parse as JSON.
		var m Message
		err = json.Unmarshal(message, &m)
		if err != nil {
			log.Println("error unmarshaling: ", err)
			break
		}
		// Save raw data for this message for further processing, but append
		// username.
		// XXX: we'll end up unmarshalling twice. We should re-think this later.
		m.realm = s.realm
		m.From = s.conn.username
		// Remarshal to m.rawdata
		rawdata, err := json.Marshal(m)
		if err != nil {
			log.Println("Error re-marshalling: ", err)
			break
		}
		m.rawdata = rawdata
		// Pass it on to the external handler.
		Hub.handler.HandleMessage(m)
		// For right now only PrivateMT should not be broadcast.
		if m.Mtype != PrivateMT {
			Hub.broadcast <- m
		}

	}
}
开发者ID:domino14,项目名称:gosports,代码行数:51,代码来源:conn.go


示例12: readPump

// readPump pumps messages from the websocket connection to the toplevel.
func (c *Client) readPump() {
	defer func() {
		c.reg.unregister <- c
		c.conn.Close()
		c.top.terminate()
	}()

	for {
		_, message, err := c.conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway,
				websocket.CloseNoStatusReceived) {
				log.Printf("readPump error: %v", err)
			}
			break
		}
		c.top.stdin.Write(message)
	}
}
开发者ID:kfl,项目名称:trymosml,代码行数:20,代码来源:client.go


示例13: readPump

// readPump pumps messages from the websocket connection to the hub.
func (c *Conn) readPump() {
	defer func() {
		hub.unregister <- c
		c.ws.Close()
	}()
	c.ws.SetReadLimit(maxMessageSize)
	c.ws.SetReadDeadline(time.Now().Add(pongWait))
	c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.ws.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v", err)
			}
			break
		}
		message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
		hub.broadcast <- message
	}
}
开发者ID:Fruchtgummi,项目名称:websocket,代码行数:21,代码来源:conn.go


示例14: read

func (c *Client) read() {
	hub := GetHub()
	defer func() {
		hub.unregister <- c
		c.con.Close()
	}()
	c.con.SetReadLimit(maxMessageSize)
	c.con.SetReadDeadline(time.Now().Add(pongWait))
	c.con.SetPongHandler(func(string) error { c.con.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		message := &SendMessage{}
		err := c.con.ReadJSON(message)
		if err != nil {
			if soc.IsUnexpectedCloseError(err, soc.CloseGoingAway) {
				log.Printf("error: %v", err)
			}
			break
		}
		message.Message = string(bytes.TrimSpace(bytes.Replace([]byte(message.Message), newline, space, -1)))
		hub.broadcast <- message
	}
}
开发者ID:Crandel,项目名称:golang_websocket_chat_demo,代码行数:22,代码来源:client.go


示例15: readMessagesLoop

// readMessagesLoop reads messages from the websocket connection.
func (c *wsConnection) readMessagesLoop(mode int) {
	// When disconnect
	defer func() {
		close(c.done)
		close(c.outboxMessages)
		close(c.inboxMessages)
	}()

	for {
		// Reset the read deadline.
		c.ws.SetReadDeadline(time.Now().Add(c.sc.pingTimeout))

		messageType, message, err := c.ws.ReadMessage()

		if err != nil {
			isUnexpectedError := websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure,
				websocket.CloseGoingAway, websocket.CloseNoStatusReceived)

			if err != io.EOF && isUnexpectedError {
				log.Error("failed to read data from websocket: %v", err)
			}

			return
		}

		switch messageType {
		case mode:
			log.Debug("received message with a payload")
			c.inboxMessages <- message
		case websocket.CloseMessage:
			log.Debug("got close message")
			return
		default:
			log.Debug("got wrong message, message dropped")
		}
	}
}
开发者ID:ZloyDyadka,项目名称:socketcrutch,代码行数:38,代码来源:ws_connection.go


示例16: readPump

// readPump pumps messages from the websocket connection to the hub.
func (c *Connection) readPump() {
	defer func() {
		c.tb.disconnected(c)
		c.ws.Close()
	}()
	c.ws.SetReadLimit(maxMessageSize)
	c.ws.SetReadDeadline(time.Now().Add(pongWait))
	c.ws.SetPongHandler(func(d string) error {
		c.ws.SetReadDeadline(time.Now().Add(pongWait))
		return nil
	})
	for {
		var event Event
		err := c.ws.ReadJSON(&event)

		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v", err)
			}
			break
		}

		log.Printf("Received event %v", event)

		switch event.Type {
		case "subscribe":
			c.Subscribed(event.Channel)
		case "message":
			for _, ch := range c.tb.Channels(event.Channel) {
				ch.Received(event)
			}
		default:
			log.Printf("unknown event command %s", event.Type)
		}
	}
}
开发者ID:jingweno,项目名称:thunderbird-chat,代码行数:37,代码来源:connection.go


示例17: readPump

func (c *Conn) readPump() {
	defer func() {
		c.ws.Close()
	}()

	c.ws.SetReadLimit(maxMessageSize)
	c.ws.SetReadDeadline(time.Now().Add(pongWait))
	c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.ws.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				Debug(fmt.Sprintf("ERROR: %v", err))
			}
			break
		}
		message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
		Debug(string(message))

		if c.readCallback != nil {
			c.readCallback(c, string(message))
		}
	}
}
开发者ID:mikeflynn,项目名称:echo-tunnel,代码行数:24,代码来源:connection.go


示例18: watch

func (i *Informer) watch() {
	const (
		// Time allowed to write a message to the peer.
		writeWait = 10 * time.Second
		// Time allowed to read the next pong message from the peer.
		pongWait = 10 * time.Second
		// Send pings to peer with this period. Must be less than pongWait.
		pingPeriod = (pongWait * 9) / 10
	)

	// write writes a message with the given message type and payload.
	writeFn := func(ws *websocket.Conn, mt int, payload []byte) error {
		ws.SetWriteDeadline(time.Now().Add(writeWait))
		return ws.WriteMessage(mt, payload)
	}

	for {
		ws, resp, err := i.wsDialer.Dial(i.wsURL, i.wsHeader)
		if err != nil {
			if err == websocket.ErrBadHandshake {
				err = fmt.Errorf("handshake failed with status %d", resp.StatusCode)
			}
			i.notifyError(err)
			continue
		}

		// TODO: Look which is the max resource limit in kubernetes (the json serialized one)
		//ws.SetReadLimit(maxResourceSize)
		ws.SetReadDeadline(time.Now().Add(pongWait))
		ws.SetPongHandler(func(string) error {
			ws.SetReadDeadline(time.Now().Add(pongWait))
			return nil
		})

		// this routine pumps messages from the hub to the websocket connection.
		go func() {
			ticker := time.NewTicker(pingPeriod)
			defer func() {
				ticker.Stop()
				ws.Close()
			}()
			for {
				select {
				case <-ticker.C:
					if err := writeFn(ws, websocket.PingMessage, []byte{}); err != nil {
						return
					}
				}
			}
		}()

	L:
		for {
			select {
			case <-i.stopChan:
				break
			default:
				v := i.rc.item()
				we := &kapi.WatchEvent{Object: v}
				if err := ws.ReadJSON(&we); err != nil {
					if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
						i.notifyError(err)
					}
					break L
				} else {
					// notify watch event
					i.notify(we)
				}
			}
		}
	}
}
开发者ID:glerchundi,项目名称:kube2nginx,代码行数:72,代码来源:client.go


示例19: ReadPump

func (connection *Connection) ReadPump() {
	defer func() {
		HubInstance.unregister <- connection
		connection.ws.Close()
	}()
	connection.ws.SetReadLimit(consts.MaxMessageSize)
	connection.ws.SetReadDeadline(time.Now().Add(consts.PongWait))
	connection.ws.SetPongHandler(func(string) error {
		connection.ws.SetReadDeadline(time.Now().Add(consts.PongWait))
		return nil
	})
	for {
		_, message, err := connection.ws.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
				log.Printf("error: %v", err)
			}
			break
		}
		messageRequest := &MessageRequest{}
		if unmarshalErr := json.Unmarshal(message, messageRequest); unmarshalErr != nil {
			// request type error.
			HubInstance.typeerr <- connection
			continue
		}
		connection.request = messageRequest
		switch messageRequest.RequestType {
		case consts.CpuMetric:
			// cpu metric request.
			HubInstance.cpumetric <- connection
		case consts.MemoryMetric:
			// memory metric request.
			HubInstance.memorymetric <- connection
		case consts.DiskMetric:
			// disk metric request.
			HubInstance.diskmetric <- connection
		case consts.DiskReadMetric:
			// disk read metric request.
			HubInstance.diskreadmetric <- connection
		case consts.NetworkReceiveMetric:
			// network receive metric request.
			HubInstance.networkreceivemetric <- connection
		case consts.NetworkTransmitMetric:
			// network transmitMetric:
			HubInstance.networktransmitmetric <- connection
		case consts.CombinMetric:
			// combin metric request.
			HubInstance.combinmetric <- connection
		case consts.NodeBootMetric:
			// node boot time metric request.
			HubInstance.nodebootmetric <- connection
		case consts.ProcessRunningMetric:
			// node process running metric request.
			HubInstance.processrunningmetric <- connection
		case consts.ProcessBlockedMetric:
			// node process blocked metric request.
			HubInstance.processblockedmetric <- connection
		case consts.ContainerLastSeenMetric:
			// container last seen metric request.
			HubInstance.containerlastseenmetric <- connection
		case consts.ContainerMemoryUsageBytesMetric:
			// container memory usage bytes metric request.
			HubInstance.containermemoryusagebytesmetric <- connection
		case consts.TotalRancherServicesMetric:
			// total rancher services metric request.
			HubInstance.totalrancherservicesmetric <- connection
		default:
			// request type error.
			HubInstance.typeerr <- connection
		}
	}
}
开发者ID:ZhenyangZhao,项目名称:metric_websocket,代码行数:72,代码来源:types.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang websocket.NewClient函数代码示例发布时间:2022-05-23
下一篇:
Golang websocket.FormatCloseMessage函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap