mirror of https://gitee.com/godoos/godoos.git
3 changed files with 288 additions and 283 deletions
@ -1,224 +1,218 @@ |
|||||
package localchat |
package localchat |
||||
|
|
||||
// import (
|
import ( |
||||
// "encoding/json"
|
"encoding/json" |
||||
// "fmt"
|
"fmt" |
||||
// "godo/libs"
|
"godo/libs" |
||||
// "io"
|
"io" |
||||
// "log"
|
"log" |
||||
// "net"
|
"net" |
||||
// "net/http"
|
"net/http" |
||||
// "os"
|
"os" |
||||
// "path/filepath"
|
"path/filepath" |
||||
// "time"
|
"time" |
||||
// )
|
) |
||||
|
|
||||
// const (
|
const ( |
||||
// fileSize = 1024 // 每个数据包的大小
|
fileSize = 1024 // 每个数据包的大小
|
||||
// )
|
) |
||||
|
|
||||
// type FileChunk struct {
|
type FileChunk struct { |
||||
// ChunkIndex int `json:"chunk_index"`
|
ChunkIndex int `json:"chunk_index"` |
||||
// Data []byte `json:"data"`
|
Data []byte `json:"data"` |
||||
// Checksum uint32 `json:"checksum"`
|
Checksum uint32 `json:"checksum"` |
||||
// Timestamp time.Time `json:"timestamp"`
|
Timestamp time.Time `json:"timestamp"` |
||||
// Filename string `json:"filename"`
|
Filename string `json:"filename"` |
||||
// }
|
} |
||||
|
|
||||
// // HandleMessage 处理 HTTP 请求
|
// HandleMessage 处理 HTTP 请求
|
||||
// func HandleMessage(w http.ResponseWriter, r *http.Request) {
|
func HandleMessage(w http.ResponseWriter, r *http.Request) { |
||||
// var msg UdpMessage
|
var msg UdpMessage |
||||
// decoder := json.NewDecoder(r.Body)
|
decoder := json.NewDecoder(r.Body) |
||||
// if err := decoder.Decode(&msg); err != nil {
|
if err := decoder.Decode(&msg); err != nil { |
||||
// http.Error(w, "Invalid request body", http.StatusBadRequest)
|
http.Error(w, "Invalid request body", http.StatusBadRequest) |
||||
// return
|
return |
||||
// }
|
} |
||||
// defer r.Body.Close()
|
defer r.Body.Close() |
||||
// err := SendToIP(msg)
|
err := SendToIP(msg) |
||||
// if err != nil {
|
if err != nil { |
||||
// http.Error(w, "Failed to send message", http.StatusInternalServerError)
|
http.Error(w, "Failed to send message", http.StatusInternalServerError) |
||||
// return
|
return |
||||
// }
|
} |
||||
// w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK) |
||||
// fmt.Fprintln(w, "Text message send successfully")
|
fmt.Fprintln(w, "Text message send successfully") |
||||
// }
|
} |
||||
|
|
||||
// func HandlerFile(w http.ResponseWriter, r *http.Request) {
|
func HandlerFile(w http.ResponseWriter, r *http.Request) { |
||||
// // 初始化多播地址
|
// 初始化多播地址
|
||||
// var msg UdpMessage
|
var msg UdpMessage |
||||
// decoder := json.NewDecoder(r.Body)
|
decoder := json.NewDecoder(r.Body) |
||||
// if err := decoder.Decode(&msg); err != nil {
|
if err := decoder.Decode(&msg); err != nil { |
||||
// http.Error(w, "Invalid request body", http.StatusBadRequest)
|
http.Error(w, "Invalid request body", http.StatusBadRequest) |
||||
// return
|
return |
||||
// }
|
} |
||||
// defer r.Body.Close()
|
defer r.Body.Close() |
||||
// toIp := msg.IP
|
toIp := msg.IP |
||||
// preferredIP, err := GetLocalIP()
|
msg.Type = "file" |
||||
// if err != nil {
|
basePath, err := libs.GetOsDir() |
||||
// http.Error(w, "Failed to get preferred IP", http.StatusInternalServerError)
|
if err != nil { |
||||
// return
|
libs.HTTPError(w, http.StatusInternalServerError, err.Error()) |
||||
// }
|
return |
||||
// msg.IP = preferredIP
|
} |
||||
// msg.Type = "file"
|
filePath := filepath.Join(basePath, msg.Message.(string)) |
||||
// basePath, err := libs.GetOsDir()
|
// 处理单个文件或整个文件夹
|
||||
// if err != nil {
|
if fileInfo, err := os.Stat(filePath); err == nil { |
||||
// libs.HTTPError(w, http.StatusInternalServerError, err.Error())
|
if fileInfo.IsDir() { |
||||
// return
|
handleDirectory(filePath, toIp, msg) |
||||
// }
|
} else { |
||||
// filePath := filepath.Join(basePath, msg.Message.(string))
|
handleFile(filePath, toIp, msg) |
||||
// // 处理单个文件或整个文件夹
|
} |
||||
// if fileInfo, err := os.Stat(filePath); err == nil {
|
} else { |
||||
// if fileInfo.IsDir() {
|
http.Error(w, "Failed to stat path", http.StatusInternalServerError) |
||||
// handleDirectory(filePath, toIp, msg)
|
return |
||||
// } else {
|
} |
||||
// handleFile(filePath, toIp, msg)
|
} |
||||
// }
|
|
||||
// } else {
|
func handleFile(filePath string, toIp string, message UdpMessage) { |
||||
// http.Error(w, "Failed to stat path", http.StatusInternalServerError)
|
// 打开文件
|
||||
// return
|
file, err := os.Open(filePath) |
||||
// }
|
if err != nil { |
||||
// }
|
log.Fatalf("Failed to open file: %v", err) |
||||
|
} |
||||
// func handleFile(filePath string, toIp string, message UdpMessage) {
|
defer file.Close() |
||||
// // 打开文件
|
|
||||
// file, err := os.Open(filePath)
|
// 获取文件大小
|
||||
// if err != nil {
|
fileInfo, err := file.Stat() |
||||
// log.Fatalf("Failed to open file: %v", err)
|
if err != nil { |
||||
// }
|
log.Fatalf("Failed to get file info: %v", err) |
||||
// defer file.Close()
|
} |
||||
|
fileSize := fileInfo.Size() |
||||
// // 获取文件大小
|
|
||||
// fileInfo, err := file.Stat()
|
// 计算需要发送的数据包数量
|
||||
// if err != nil {
|
numChunks := (fileSize + fileSize - 1) / fileSize |
||||
// log.Fatalf("Failed to get file info: %v", err)
|
|
||||
// }
|
// 发送文件
|
||||
// fileSize := fileInfo.Size()
|
SendFile(file, int(numChunks), toIp, message) |
||||
|
} |
||||
// // 计算需要发送的数据包数量
|
|
||||
// numChunks := (fileSize + fileSize - 1) / fileSize
|
func handleDirectory(dirPath string, toIp string, message UdpMessage) { |
||||
|
err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error { |
||||
// // 发送文件
|
if err != nil { |
||||
// SendFile(file, int(numChunks), toIp, message)
|
return err |
||||
// }
|
} |
||||
|
if !info.IsDir() { |
||||
// func handleDirectory(dirPath string, toIp string, message UdpMessage) {
|
handleFile(path, toIp, message) |
||||
// err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
|
} |
||||
// if err != nil {
|
return nil |
||||
// return err
|
}) |
||||
// }
|
if err != nil { |
||||
// if !info.IsDir() {
|
log.Fatalf("Failed to walk directory: %v", err) |
||||
// handleFile(path, toIp, message)
|
} |
||||
// }
|
} |
||||
// return nil
|
func SendFile(file *os.File, numChunks int, toIp string, message UdpMessage) { |
||||
// })
|
// 逐块读取文件并发送
|
||||
// if err != nil {
|
for i := 0; i < numChunks; i++ { |
||||
// log.Fatalf("Failed to walk directory: %v", err)
|
var chunkData [fileSize]byte |
||||
// }
|
n, err := file.Read(chunkData[:]) |
||||
// }
|
if err != nil && err != io.EOF { |
||||
// func SendFile(file *os.File, numChunks int, toIp string, message UdpMessage) {
|
log.Fatalf("Failed to read file chunk: %v", err) |
||||
// // 逐块读取文件并发送
|
} |
||||
// for i := 0; i < numChunks; i++ {
|
|
||||
// var chunkData [fileSize]byte
|
// 创建文件块
|
||||
// n, err := file.Read(chunkData[:])
|
chunk := FileChunk{ |
||||
// if err != nil && err != io.EOF {
|
ChunkIndex: i, |
||||
// log.Fatalf("Failed to read file chunk: %v", err)
|
Data: chunkData[:n], |
||||
// }
|
Checksum: calculateChecksum(chunkData[:n]), |
||||
|
Timestamp: time.Now(), |
||||
// // 创建文件块
|
Filename: filepath.Base(file.Name()), |
||||
// chunk := FileChunk{
|
} |
||||
// ChunkIndex: i,
|
message.Message = chunk |
||||
// Data: chunkData[:n],
|
// 将文件块转换为 JSON 格式
|
||||
// Checksum: calculateChecksum(chunkData[:n]),
|
data, err := json.Marshal(message) |
||||
// Timestamp: time.Now(),
|
if err != nil { |
||||
// Filename: filepath.Base(file.Name()),
|
log.Fatalf("Failed to marshal chunk: %v", err) |
||||
// }
|
} |
||||
// message.Message = chunk
|
|
||||
// // 将文件块转换为 JSON 格式
|
// 发送文件块
|
||||
// data, err := json.Marshal(message)
|
addr, err := net.ResolveUDPAddr("udp4", toIp) |
||||
// if err != nil {
|
if err != nil { |
||||
// log.Fatalf("Failed to marshal chunk: %v", err)
|
log.Fatalf("Failed to resolve UDP address: %v", err) |
||||
// }
|
} |
||||
|
|
||||
// // 发送文件块
|
conn, err := net.DialUDP("udp4", nil, addr) |
||||
// addr, err := net.ResolveUDPAddr("udp4", toIp)
|
if err != nil { |
||||
// if err != nil {
|
log.Fatalf("Failed to dial UDP address: %v", err) |
||||
// log.Fatalf("Failed to resolve UDP address: %v", err)
|
} |
||||
// }
|
defer conn.Close() |
||||
|
|
||||
// conn, err := net.DialUDP("udp4", nil, addr)
|
_, err = conn.Write(data) |
||||
// if err != nil {
|
if err != nil { |
||||
// log.Fatalf("Failed to dial UDP address: %v", err)
|
log.Printf("Failed to write data: %v", err) |
||||
// }
|
} |
||||
// defer conn.Close()
|
|
||||
|
fmt.Printf("发送文件块 %d 到 %s 成功\n", i, toIp) |
||||
// _, err = conn.Write(data)
|
} |
||||
// if err != nil {
|
} |
||||
// log.Printf("Failed to write data: %v", err)
|
func RecieveFile(msg UdpMessage) { |
||||
// }
|
chunk := msg.Message.(FileChunk) |
||||
|
|
||||
// fmt.Printf("发送文件块 %d 到 %s 成功\n", i, toIp)
|
// 验证校验和
|
||||
// }
|
calculatedChecksum := calculateChecksum(chunk.Data) |
||||
// }
|
if calculatedChecksum != chunk.Checksum { |
||||
// func RecieveFile(msg UdpMessage) {
|
fmt.Printf("Checksum mismatch for chunk %d from %s\n", chunk.ChunkIndex, msg.IP) |
||||
// chunk := msg.Message.(FileChunk)
|
return |
||||
|
} |
||||
// // 验证校验和
|
|
||||
// calculatedChecksum := calculateChecksum(chunk.Data)
|
baseDir, err := libs.GetOsDir() |
||||
// if calculatedChecksum != chunk.Checksum {
|
if err != nil { |
||||
// fmt.Printf("Checksum mismatch for chunk %d from %s\n", chunk.ChunkIndex, msg.IP)
|
log.Printf("Failed to get OS directory: %v", err) |
||||
// return
|
return |
||||
// }
|
} |
||||
|
|
||||
// baseDir, err := libs.GetOsDir()
|
// 创建接收文件的目录
|
||||
// if err != nil {
|
receiveDir := filepath.Join(baseDir, "C", "Users", "Reciv", time.Now().Format("2006-01-02")) |
||||
// log.Printf("Failed to get OS directory: %v", err)
|
if !libs.PathExists(receiveDir) { |
||||
// return
|
err := os.MkdirAll(receiveDir, 0755) |
||||
// }
|
if err != nil { |
||||
|
log.Printf("Failed to create receive directory: %v", err) |
||||
// // 创建接收文件的目录
|
return |
||||
// receiveDir := filepath.Join(baseDir, "C", "Users", "Reciv", time.Now().Format("2006-01-02"))
|
} |
||||
// if !libs.PathExists(receiveDir) {
|
} |
||||
// err := os.MkdirAll(receiveDir, 0755)
|
|
||||
// if err != nil {
|
// 确定文件路径
|
||||
// log.Printf("Failed to create receive directory: %v", err)
|
filePath := filepath.Join(receiveDir, chunk.Filename) |
||||
// return
|
|
||||
// }
|
// 如果文件不存在,则创建新文件
|
||||
// }
|
if _, err := os.Stat(filePath); os.IsNotExist(err) { |
||||
|
file, err := os.Create(filePath) |
||||
// // 确定文件路径
|
if err != nil { |
||||
// filePath := filepath.Join(receiveDir, chunk.Filename)
|
log.Printf("Failed to create file: %v", err) |
||||
|
return |
||||
// // 如果文件不存在,则创建新文件
|
} |
||||
// if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
defer file.Close() |
||||
// file, err := os.Create(filePath)
|
} |
||||
// if err != nil {
|
|
||||
// log.Printf("Failed to create file: %v", err)
|
// 打开或追加到现有文件
|
||||
// return
|
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0644) |
||||
// }
|
if err != nil { |
||||
// defer file.Close()
|
log.Printf("Failed to open file: %v", err) |
||||
// }
|
return |
||||
|
} |
||||
// // 打开或追加到现有文件
|
defer file.Close() |
||||
// file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0644)
|
|
||||
// if err != nil {
|
// 写入数据
|
||||
// log.Printf("Failed to open file: %v", err)
|
_, err = file.Write(chunk.Data) |
||||
// return
|
if err != nil { |
||||
// }
|
log.Printf("Failed to write data to file: %v", err) |
||||
// defer file.Close()
|
return |
||||
|
} |
||||
// // 写入数据
|
|
||||
// _, err = file.Write(chunk.Data)
|
fmt.Printf("接收到文件块 %d 从 %s 成功\n", chunk.ChunkIndex, msg.IP) |
||||
// if err != nil {
|
} |
||||
// log.Printf("Failed to write data to file: %v", err)
|
func calculateChecksum(data []byte) uint32 { |
||||
// return
|
checksum := uint32(0) |
||||
// }
|
for _, b := range data { |
||||
|
checksum += uint32(b) |
||||
// fmt.Printf("接收到文件块 %d 从 %s 成功\n", chunk.ChunkIndex, msg.IP)
|
} |
||||
// }
|
return checksum |
||||
// func calculateChecksum(data []byte) uint32 {
|
} |
||||
// checksum := uint32(0)
|
|
||||
// for _, b := range data {
|
|
||||
// checksum += uint32(b)
|
|
||||
// }
|
|
||||
// return checksum
|
|
||||
// }
|
|
||||
|
Loading…
Reference in new issue