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


Golang Conn.Write方法代码示例

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


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

示例1: handleStatistic

func handleStatistic(ws *websocket.Conn) {
	for k, v := range ws.Config().Header {
		log.Debug.Println(k, " - ", v)
	}

	ws.Write([]byte("Hi"))
}
开发者ID:Avialeta,项目名称:API,代码行数:7,代码来源:statistic.go

示例2: addLogs

func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	err = scanLogs(ws)
	if err != nil {
		return
	}
}
开发者ID:pedrosnk,项目名称:tsuru,代码行数:29,代码来源:log.go

示例3: AppLogs

func AppLogs(ws *websocket.Conn) error {
	defer ws.Close()

	app := mux.Vars(ws.Request())["app"]

	a, err := models.GetApp(app)

	if awsError(err) == "ValidationError" {
		return fmt.Errorf("no such app: %s", app)
	}

	if err != nil {
		return err
	}

	logs := make(chan []byte)
	done := make(chan bool)

	a.SubscribeLogs(logs, done)

	for data := range logs {
		ws.Write(data)
	}

	return nil
}
开发者ID:jbuck,项目名称:rack,代码行数:26,代码来源:apps.go

示例4: handleTrafficWS

func handleTrafficWS(conn *websocket.Conn) {
	trafficMutex.Lock()
	for _, traf := range traffic {
		if !traf.Position_valid { // Don't send unless a valid position exists.
			continue
		}
		trafficJSON, _ := json.Marshal(&traf)
		conn.Write(trafficJSON)
	}
	trafficMutex.Unlock()
	// Subscribe the socket to receive updates.
	trafficUpdate.AddSocket(conn)

	// Connection closes when function returns. Since uibroadcast is writing and we don't need to read anything (for now), just keep it busy.
	for {
		buf := make([]byte, 1024)
		_, err := conn.Read(buf)
		if err != nil {
			break
		}
		if buf[0] != 0 { // Dummy.
			continue
		}
		time.Sleep(1 * time.Second)
	}
}
开发者ID:speedbird21,项目名称:stratux,代码行数:26,代码来源:managementinterface.go

示例5: socketHandler

func socketHandler(ws *websocket.Conn) {
	for {
		receivedStream := make([]byte, 256)
		byteCount, err := ws.Read(receivedStream)

		if err != nil {
			return
		}

		if byteCount > 0 {
			inputHeaders := make(map[string]string)

			decode_err := json.Unmarshal(receivedStream[:byteCount], &inputHeaders)

			if decode_err != nil {
				return
			}
			out := runPlugins("secred_key", "endpoint_XXX", "consumer_XXX")

			jsonOut, encode_err := json.Marshal(out.Headers)
			if encode_err != nil {
				return
			}

			ws.Write(jsonOut)
		}
	}
}
开发者ID:mariusmagureanu,项目名称:vaed,代码行数:28,代码来源:main.go

示例6: SendMetrics

// sendMetrics sends the current state of tasks to the F12 API
func SendMetrics(ws *websocket.Conn, userID string, tasks map[string]demand.Task) error {
	var err error = nil
	var index int = 0

	metrics := metrics{
		Tasks:     make([]taskMetrics, len(tasks)),
		CreatedAt: time.Now().Unix(),
	}

	for name, task := range tasks {
		metrics.Tasks[index] = taskMetrics{App: name, RunningCount: task.Running, PendingCount: task.Requested}
		index++
	}

	payload := metricsPayload{
		User:    userID,
		Metrics: metrics,
	}

	b, err := json.Marshal(payload)
	if err != nil {
		return fmt.Errorf("Failed to encode API json. %v", err)
	}

	_, err = ws.Write(b)
	if err != nil {
		return fmt.Errorf("Failed to send metrics: %v", err)
	}

	return err
}
开发者ID:mehulsbhatt,项目名称:force12,代码行数:32,代码来源:metrics.go

示例7: handleStatusWS

func handleStatusWS(conn *websocket.Conn) {
	//	log.Printf("Web client connected.\n")

	timer := time.NewTicker(1 * time.Second)
	for {
		// The below is not used, but should be if something needs to be streamed from the web client ever in the future.
		/*		var msg SettingMessage
				err := websocket.JSON.Receive(conn, &msg)
				if err == io.EOF {
					break
				} else if err != nil {
					log.Printf("handleStatusWS: %s\n", err.Error())
				} else {
					// Use 'msg'.
				}
		*/

		// Send status.
		<-timer.C
		update, _ := json.Marshal(&globalStatus)
		_, err := conn.Write(update)

		if err != nil {
			//			log.Printf("Web client disconnected.\n")
			break
		}
	}
}
开发者ID:speedbird21,项目名称:stratux,代码行数:28,代码来源:managementinterface.go

示例8: configureCertificate

func configureCertificate(ws *websocket.Conn, httpsCertFileContent string, httpsKeyFileContent string) (bool, error) {
	if len(httpsCertFileContent) > 0 {
		httpsCertFilePath := beego.AppConfig.String("HTTPSCertFile")
		err := ioutil.WriteFile(httpsCertFilePath, []byte(httpsCertFileContent), 0644)
		if err != nil {
			return false, err
		}
		ws.Write([]byte("The GUI certificate is replaced\n"))
	}

	if len(httpsKeyFileContent) > 0 {
		httpsKeyFilePath := beego.AppConfig.String("HTTPSKeyFile")
		err := ioutil.WriteFile(httpsKeyFilePath, []byte(httpsKeyFileContent), 0644)
		if err != nil {
			return false, err
		}
		ws.Write([]byte("The GUI key is replaced\n"))
	}

	if len(httpsCertFileContent) > 0 || len(httpsKeyFileContent) > 0 {
		return true, nil
	} else {
		return false, nil
	}
}
开发者ID:cloudawan,项目名称:cloudone_gui,代码行数:25,代码来源:index.go

示例9: Handlews2

func Handlews2(ws *websocket.Conn) {
	var stats types.Stats
	m := NewMonMan()
	var c []Containers
	var oc []Containers

	cli, err := client.NewEnvClient()
	if err != nil {
		fmt.Println(err)
	}
	for {
		fmt.Println("Elements copied: ", copy(oc, c))
		m.GetContainer()
		for n, cont := range m.ID {
			r, _ := cli.ContainerStats(context.Background(), cont, false)
			b, _ := ioutil.ReadAll(r.Body)
			json.Unmarshal(b, &stats)
			tmp := Containers{calculateCPUPercent(stats.PreCPUStats, stats.CPUStats), stats.MemoryStats.Usage, m.User[n], 0}
			c = append(c, tmp)
		}
		fc := UpdateList(oc, c)
		fmt.Println("New List: ", c)
		fmt.Println("Old List: ", oc)
		fmt.Println("Final List: ", fc)
		b, _ := json.Marshal(fc)
		ws.Write(b)
		time.Sleep(1000 * time.Millisecond)
	}
}
开发者ID:LeadisJourney,项目名称:backend-compilation,代码行数:29,代码来源:main.go

示例10: wsServer

func wsServer(ws *websocket.Conn) {
	var buf string
	defer func() {
		if err := ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		} else {
			log.Println("Websocket closed")
		}
	}()
	//q := ws.Request().URL.Query()
	//name := q.Get("name")
	stopped := false
	ticker := time.Tick(time.Duration(1) * time.Second)
	for !stopped {
		select {
		case <-ticker:
			val := expvar.Get(metricsVar)
			if val == nil {
				buf = ""
			} else {
				buf = val.String()
			}
			_, err := ws.Write([]byte(buf))
			if err != nil {
				log.Printf("Websocket error: %s\n", err.Error())
				stopped = true
			}

		}
	}
}
开发者ID:millken,项目名称:kaman,代码行数:31,代码来源:server.go

示例11: outLoop

func outLoop(ws *websocket.Conn, out <-chan []byte, errors chan<- error) {
	for msg := range out {
		_, err := ws.Write(msg)
		if err != nil {
			errors <- err
		}
	}
}
开发者ID:jmptrader,项目名称:wsd,代码行数:8,代码来源:main.go

示例12: WSWrite

// WSWrite sends STDIN lines to a websocket server.
func WSWrite(ws *websocket.Conn) {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		t := scanner.Text()
		ws.Write([]byte(t))
		fmt.Printf(">> %s\n", t)
	}
}
开发者ID:ajoulie,项目名称:goa,代码行数:9,代码来源:cli.go

示例13: execContainer

func (a *Api) execContainer(ws *websocket.Conn) {
	qry := ws.Request().URL.Query()
	containerId := qry.Get("id")
	command := qry.Get("cmd")
	ttyWidth := qry.Get("w")
	ttyHeight := qry.Get("h")
	token := qry.Get("token")
	cmd := strings.Split(command, ",")

	if !a.manager.ValidateConsoleSessionToken(containerId, token) {
		ws.Write([]byte("unauthorized"))
		ws.Close()
		return
	}

	log.Debugf("starting exec session: container=%s cmd=%s", containerId, command)
	clientUrl := a.manager.DockerClient().URL

	execConfig := &dockerclient.ExecConfig{
		AttachStdin:  true,
		AttachStdout: true,
		AttachStderr: true,
		Tty:          true,
		Cmd:          cmd,
		Container:    containerId,
		Detach:       true,
	}

	execId, err := a.manager.DockerClient().ExecCreate(execConfig)
	if err != nil {
		log.Errorf("error calling exec: %s", err)
		return
	}

	if err := a.hijack(clientUrl.Host, "POST", "/exec/"+execId+"/start", true, ws, ws, ws, nil, nil); err != nil {
		log.Errorf("error during hijack: %s", err)
		return
	}

	// resize
	w, err := strconv.Atoi(ttyWidth)
	if err != nil {
		log.Error(err)
		return
	}

	h, err := strconv.Atoi(ttyHeight)
	if err != nil {
		log.Error(err)
		return
	}

	if err := a.manager.DockerClient().ExecResize(execId, w, h); err != nil {
		log.Errorf("error resizing exec tty: %s", err)
		return
	}

}
开发者ID:CM44,项目名称:shipyard,代码行数:58,代码来源:exec.go

示例14: wsSend

// send a formated reply
func wsSend(ws *websocket.Conn, action, txt string) {
	response, err := json.Marshal(msgCommon{
		Cmd:  action,
		Data: txt,
	})
	if err == nil {
		ws.Write(response)
	}
}
开发者ID:toorop,项目名称:gotchat,代码行数:10,代码来源:chat.go

示例15: addLogs

func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	logCh, errCh := app.LogReceiver()
	scanner := bufio.NewScanner(ws)
	for scanner.Scan() {
		var entry app.Applog
		data := bytes.TrimSpace(scanner.Bytes())
		if len(data) == 0 {
			continue
		}
		err = json.Unmarshal(data, &entry)
		if err != nil {
			close(logCh)
			err = fmt.Errorf("wslogs: parsing log line %q: %s", string(data), err)
			return
		}
		select {
		case logCh <- &entry:
		case err := <-errCh:
			close(logCh)
			err = fmt.Errorf("wslogs: storing log: %s", err)
			return
		}
	}
	close(logCh)
	err = scanner.Err()
	if err != nil {
		err = fmt.Errorf("wslogs: waiting for log data: %s", err)
		return
	}
	err = <-errCh
	if err != nil {
		err = fmt.Errorf("wslogs: storing log: %s", err)
	}
}
开发者ID:Zapelini,项目名称:tsuru,代码行数:57,代码来源:log.go


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