示例#1
0
func (w *webserver) live(resp http.ResponseWriter, req *http.Request) {
	//get our feeder registered
	wsf := &liveWSFeeder{
		ch: make(chan namedBwSample, chanBufferSize),
	}
	id, err := w.lf.RegisterLiveFeeder(wsf)
	if err != nil {
		resp.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer w.lf.DeregisterLiveFeeder(id)

	//upgrade to a websocket
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	conn, err := upgrader.Upgrade(resp, req, nil)
	if err != nil {
		return
	}
	defer conn.Close()

	//start feeding and relaying
	for s := range wsf.ch {
		if err := websocket.WriteJSON(conn, s); err != nil {
			break
		}
	}
}
示例#2
0
文件: main.go 项目: jgastal/mural
func notifyUsers(msg message) {
	for e := clients.Front(); e != nil; e = e.Next() {
		ws := e.Value.(*websocket.Conn)
		log.Printf("Notifying user %p of new message", ws)
		go websocket.WriteJSON(ws, msg)
	}
}
示例#3
0
func (container *container) Run(processSpec garden.ProcessSpec, processIO garden.ProcessIO) (garden.Process, error) {
	wsUri := container.client.RunURL(container.Handle())
	ws, _, err := websocket.DefaultDialer.Dial(wsUri, nil)
	if err != nil {
		return nil, err
	}
	websocket.WriteJSON(ws, ProcessStreamEvent{
		MessageType:    "run",
		ApiProcessSpec: processSpec,
	})

	proc := process.NewDotNetProcess(container.Handle(), container.client)
	pidChannel := make(chan uint32)

	streamWebsocketIOToContainerizer(ws, processIO)
	go func() {
		exitCode, err := streamWebsocketIOFromContainerizer(ws, pidChannel, processIO)
		proc.StreamOpen <- process.DotNetProcessExitStatus{exitCode, err}
		close(proc.StreamOpen)
	}()

	proc.Pid = <-pidChannel

	return proc, nil
}
func (server *TestWebSocketServer) createWebSocketHandler(containerId string) {
	testHandler := func(w http.ResponseWriter, r *http.Request) {
		ws, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			if _, ok := err.(websocket.HandshakeError); !ok {
				panic(err)
			}
			return
		}
		defer ws.Close()

		server.handlerWS = ws
		for {
			var streamEvent container.ProcessStreamEvent
			err := websocket.ReadJSON(ws, &streamEvent)
			if err != nil {
				continue
			}
			server.events = append(server.events, streamEvent)
			if streamEvent.MessageType == "run" {
				err = websocket.WriteJSON(ws, container.ProcessStreamEvent{
					MessageType: "pid",
					Data:        "5432",
				})
				if err != nil {
					panic(err)
				}
			}
		}
	}

	server.router.HandleFunc("/api/containers/"+containerId+"/run", testHandler)
}
示例#5
0
func pushUsers(db *sql.DB, conns []*websocket.Conn) {
	users := fetchUsers(db)
	for _, conn := range conns {
		if nil == users {
			users = []User{}
		}
		websocket.WriteJSON(conn, users)
	}
}
示例#6
0
func (c *connection) writer() {
	for message := range c.send {
		err := websocket.WriteJSON(c.ws, message)
		if err != nil {
			break
		}
	}
	c.ws.Close()
}
示例#7
0
func (s *server) dataFeedHandler(w http.ResponseWriter, r *http.Request) {
	var (
		lastPing time.Time
		lastPong time.Time
	)

	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}

	conn.SetPongHandler(func(s string) error {
		lastPong = time.Now()
		return nil
	})

	// read and discard all messages
	go func(c *websocket.Conn) {
		for {
			if _, _, err := c.NextReader(); err != nil {
				c.Close()
				break
			}
		}
	}(conn)

	c := s.addConsumer()

	defer func() {
		s.removeConsumer(c.id)
		conn.Close()
	}()

	var i uint

	for u := range c.c {
		websocket.WriteJSON(conn, u)
		i += 1

		if i%10 == 0 {
			if diff := lastPing.Sub(lastPong); diff > time.Second*60 {
				return
			}
			now := time.Now()
			if err := conn.WriteControl(websocket.PingMessage, nil, now.Add(time.Second)); err != nil {
				return
			}
			lastPing = now
		}
	}
}
示例#8
0
func (this *Protocol) Welcome(ws *websocket.Conn, id int) (err error) {
	//WMAP Welcome
	beego.Info("Open connection, say Welcome")
	msg := &messages.WelcomeMessage{}
	msg.Id = id
	err = websocket.WriteJSON(ws, msg.Array())
	if err != nil {
		return
	}
	beego.Info("Welcome message sent")

	return nil
}
示例#9
0
文件: client.go 项目: nizsheanez/ria
// Listen write request via chanel
func (this *Client) listenWrite() {
	for {
		// send message to the client
		select {
		case rawMsg := <-this.messagesCh:
			message, ok := rawMsg.(*messages.ResultMessage)
			if !ok {
				this.server.Err(errors.New(fmt.Sprintf("Can't case %T to RpcMessage", rawMsg)))
			}

			err := websocket.WriteJSON(this.ws, message.Array())
			if err != nil {
				this.server.Err(err)
			}

			// receive done request
		case <-this.doneCh:
			this.server.Del(this)
			this.doneCh <- true // for listenRead method
			return
		}
	}
}
			p, err := container.Run(garden.ProcessSpec{}, garden.ProcessIO{
				Stdin: stdin,
			})
			Expect(err).ShouldNot(HaveOccurred())
			Expect(p.ID()).To(Equal("5432"))
		})

		It("streams stdout from the websocket back through garden", func() {
			stdout := gbytes.NewBuffer()
			_, err := container.Run(garden.ProcessSpec{}, garden.ProcessIO{
				Stdout: stdout,
			})
			Expect(err).ShouldNot(HaveOccurred())

			websocket.WriteJSON(testServer.handlerWS, netContainer.ProcessStreamEvent{
				MessageType: "stdout",
				Data:        "hello from windows",
			})
			Eventually(stdout).Should(gbytes.Say("hello from windows"))
		})

		It("streams stderr from the websocket back through garden", func() {
			stderr := gbytes.NewBuffer()
			_, err := container.Run(garden.ProcessSpec{}, garden.ProcessIO{
				Stderr: stderr,
			})
			Expect(err).ShouldNot(HaveOccurred())

			websocket.WriteJSON(testServer.handlerWS, netContainer.ProcessStreamEvent{
				MessageType: "stderr",
				Data:        "error from windows",
			})
示例#11
0
文件: main.go 项目: scrivy/findme-go
func wsHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		logErr(err)
		return
	}

	err = websocket.WriteJSON(conn, getAllLocations())
	if err != nil {
		logErr(err)
	}

	id := <-getIdChan
	err = conn.WriteJSON(message{
		Action: "yourId",
		Data:   id,
	})
	if err != nil {
		logErr(err)
	}

	c := client{
		conn:          conn,
		location:      location{Id: id},
		id:            id,
		closeChan:     make(chan bool),
		lastRxMessage: time.Now(),
	}
	conn.SetPongHandler(connPongHandler(&c))
	idToConnMapMutex.Lock()
	idToConnMap[id] = &c
	log.Printf("%d open websockets", len(idToConnMap))
	idToConnMapMutex.Unlock()

	go func(c *client) {
		ticker := time.NewTicker(time.Second)
		var jsonBytes []byte
		var locations []location
		var err error
		for {
			select {
			case <-ticker.C:
				locations = []location{}
				updatesMutex.RLock()
				if len(updatesMap) > 0 {
					for id, l := range updatesMap {
						if id != c.id {
							locations = append(locations, l)
						}
					}
				}
				updatesMutex.RUnlock()
				if len(locations) > 0 {
					jsonBytes, err = json.Marshal(message{
						Action: "allLocations",
						Data:   locations,
					})
					if err != nil {
						logErr(err)
						continue
					}
					c.send(&jsonBytes)
				}
			case <-c.closeChan:
				ticker.Stop()
				return
			}
		}
	}(&c)

	var m message
	var jsonBytes []byte
	for {
		messageType, r, err := conn.NextReader()
		if err != nil {
			switch err {
			//			case io.EOF:
			default:
				switch err.Error() {
				case "websocket: close 1006 (abnormal closure): unexpected EOF":
				default:
					log.Println("conn.NextReader err:", err)
				}
			}
			conn.Close()
			break
		}

		c.lastRxMessage = time.Now()

		switch messageType {
		case websocket.TextMessage:
			jsonBytes, err = ioutil.ReadAll(r)
			if err != nil {
				logErr(err)
				continue
			}

			json.Unmarshal(jsonBytes, &m)

			switch m.Action {
			case "updateLocation":
				data := m.Data.(map[string]interface{})
				latlng, ok := data["latlng"].([]interface{})
				if !ok || len(latlng) != 2 {
					continue
				}
				lat, ok := latlng[0].(float64)
				if !ok {
					continue
				}
				lng, ok := latlng[1].(float64)
				if !ok {
					continue
				}
				accuracy, ok := data["accuracy"].(float64)
				if !ok {
					continue
				}

				l := location{
					Id:       id,
					Accuracy: accuracy,
					Latlng:   []float64{lat, lng},
				}
				c.mutex.Lock()
				c.location = l
				c.mutex.Unlock()

				getUpdate <- l
			case "oldId":
				oldId, ok := m.Data.(string)
				if !ok {
					continue
				}

				idToConnMapMutex.Lock()
				oldConn, ok := idToConnMap[oldId]
				delete(idToConnMap, oldId)
				idToConnMapMutex.Unlock()

				if ok {
					oldIdMessage := message{
						Action: "oldId",
						Data: map[string]string{
							"OldId": oldId,
							"NewId": id,
						},
					}
					jsonBytes, err = json.Marshal(oldIdMessage)
					if err != nil {
						logErr(err)
						continue
					}
					sendMessageToAll(&jsonBytes, &id)
					oldConn.close()
					log.Println("deleted oldId")
				}
			default:
				log.Printf("%s: %+v\n", m.Action, m.Data)
			}
		default:
			log.Printf("messageType: %#v\n", messageType)
		}
	}
}