简体   繁体   中英

Golang Websocket detecting file message and writing it if more than 1 ws frame byte

I need to save each new picture in one file, which is sent by several frames through websockets. Here is code of my file:

package main

import (
"fmt"
"golang.org/x/net/websocket"
"log"
"net/http"
"os"
"time"
)

var (
dirPath string
test    byte
lenFile int
)

func check(e error) {
if e != nil {
    panic(e)
}
}

func ChatServer(ws *websocket.Conn) {   
defer ws.Close()
var test []byte
var payload []byte
for {
    err := websocket.Message.Receive(ws, &payload)
    if err != nil {
        log.Println(err)
    }

    fmt.Println("Payload: ", len(payload))

    test = append(test, payload...)
    fmt.Println("Test: ", len(test))

    fo, err := os.Create(fmt.Sprintf("./%d.png", time.Now().UnixNano()))
    check(err)
    _, err = fo.Write(test)
    check(err)
    fo.Close()
}
 log.Print("DONE")

}

func main() {
if len(os.Args) < 2 {
    log.Fatal("Usage: chatExample <dir>")
}

dirPath = os.Args[1]

fmt.Println("Starting... ")

http.Handle("/", http.FileServer(http.Dir(dirPath)))
http.Handle("/ws", websocket.Handler(ChatServer))

err := http.ListenAndServe(":3000", nil)

if err != nil {
    log.Fatal("ListenAndServe ", err)
}
}

And here is my results of downloading two files in order:

每个ws帧的控制台字节记录 我发送了两张图片 文件系统目录中的结果 So I need save only two files (images) if I send two files, not three. Also I need to save two different files, I have to somehow detect new file from websocket connect.

The sender fragments one of the messages into two frames. Because the x/net/websocket API exposes frames instead of messages , the application writes three files.

It's not possible to detect message boundaries using the x/net/websocket package. Use the gorilla/websocket package instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM