go socket传输文件过程中 有时会发生崩溃
代码如下
package main
import (
"bufio"
"encoding/binary"
"fmt"
"io"
"log"
"net"
"os"
)
func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
// Read file name
fileName, _ := bufio.NewReader(conn).ReadString('\n')
fileName = fileName[:len(fileName)-1] // Remove newline character
// Read file size
var fileSize int64
binary.Read(conn, binary.LittleEndian, &fileSize)
// Create file
file, err := os.Create("received_" + fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Read file content
_, err = io.CopyN(file, conn, fileSize)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Received file: %s\n", fileName)
}