duangu1033
2016-03-09 23:14
浏览 62
已采纳

Golang Websocket检测文件消息并在超过1 ws帧字节的情况下将其写入

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:

Console logging of bytes every ws frame Two images that I sent Result in filesystem catalog 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.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duansao20000508 2016-03-10 00:17
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题