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