当前位置:网站首页>Golang -- realize file transfer
Golang -- realize file transfer
2022-07-03 04:24:00 【Java mage】
With the help of TCP Complete the file transfer , The basic idea is as follows :
- The sender ( client ) Send the file name to the server , The server saves the file name .
- The receiving party ( Server side ) Return a message to the client ok, Confirm that the file name is saved successfully .
- The sender ( client ) After receiving the message , Start sending file data to the server .
- The receiving party ( Server side ) Read file contents , Write to the previously saved file .
First get the file name . With the help of os In bag stat()
Function to get file attribute information . The file attribute returned by the function contains the file name and file size .Stat Parameters name What is passed in is the absolute path of file access .FileInfo Medium Name() Function can extract the list of files .
func Stat(name string) (FileInfo, error)
type FileInfo interface {
Name() string
Size() int64
Mode() FileMode
ModTime() time.Time
IsDir() bool
Sys() interface{
}
}
The sender :
package main
import (
"fmt"
"io"
"net"
"os"
)
func sendFile(conn net.Conn, filePath string) {
// Read only open file
f, err := os.Open(filePath)
if err != nil {
fmt.Println("os.Open err:", err)
return
}
defer f.Close()
// From this document , Reading data , Write to the network receiver . How much do you read , How much to write . Wholly intact .
buf := make([]byte, 1024)
for {
n, err := f.Read(buf)
if err != nil {
if err == io.EOF {
fmt.Println(" Send file complete .")
} else {
fmt.Println("os.Open err:", err)
}
return
}
// Write to the network socket in
_, err = conn.Write(buf[:n])
if err != nil {
fmt.Println("conn.Write err:", err)
return
}
}
}
func main() {
list := os.Args // Get command line parameters
if len(list) != 2 {
fmt.Println(" The format is :go run xxx.go File absolute path ")
return
}
// extract The absolute path to the file
filePath := list[1]
// Extract filename
fileInfo, err := os.Stat(filePath)
if err != nil {
fmt.Println("os.Stat err:", err)
return
}
fileName := fileInfo.Name()
// Initiate a connection request
conn, err := net.Dial("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("net.Dial err:", err)
return
}
defer conn.Close()
// Send the file name to The receiver
_, err = conn.Write([]byte(fileName))
if err != nil {
fmt.Println("conn.Write err:", err)
return
}
// Read the message sent back by the server OK
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err:", err)
return
}
if "ok" == string(buf[:n]) {
// Write the contents of the file to the server —— With the help of conn
sendFile(conn, filePath)
}
}
The receiver :
package main
import (
"fmt"
"net"
"os"
)
func recvFile(conn net.Conn, fileName string) {
// Create a new file by file name
f, err := os.Create(fileName)
if err != nil {
fmt.Println("os.Create err:", err)
return
}
defer f.Close()
// from Read data in the network , Write to local file
buf := make([]byte, 1024)
for {
n, _ := conn.Read(buf)
if n == 0 {
fmt.Println(" Receive file complete .")
return
}
// Write to local file , How much do you read , How much to write .
f.Write(buf[:n])
}
}
func main() {
// Create a for listening socket
listener, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println(" net.Listen err:", err)
return
}
defer listener.Close()
fmt.Println(" The receiving end is started successfully , Wait for the sender to send the file !")
// Blocking monitor
conn, err := listener.Accept()
if err != nil {
fmt.Println(" listener.Accept() err:", err)
return
}
defer conn.Close()
// Get the file name , preservation
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(" conn.Read err:", err)
return
}
fileName := string(buf[:n])
// Write back ok To the sender
conn.Write([]byte("ok"))
// Get file content
recvFile(conn, fileName)
}
边栏推荐
- arthas watch 抓取入参的某个字段/属性
- redis 持久化原理
- [fairseq] error: typeerror:_ broadcast_ coalesced(): incompatible function arguments
- FFMpeg filter
- Kubernetes源码分析(一)
- 解决bp中文乱码
- [dynamic programming] subsequence problem
- CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强
- FuncS sh file not found when using the benchmarksql tool to test kingbases
- Xrandr modify resolution and refresh rate
猜你喜欢
FuncS sh file not found when using the benchmarksql tool to test kingbases
540. Single element in ordered array
Which Bluetooth headset is cost-effective? Four Bluetooth headsets with high cost performance are recommended
Pdf editing tool movavi pdfchef 2022 direct download
P35-P41 fourth_ context
redis 持久化原理
跨境电商多商户系统怎么选
Introduction of pointer variables in function parameters
Two points -leetcode-540 A single element in an ordered array
Daily question - ugly number
随机推荐
FFMpeg filter
X-ray normal based contour rendering
redis 持久化原理
Data Lake three swordsmen -- comparative analysis of delta, Hudi and iceberg
Jincang KFS data bidirectional synchronization scenario deployment
C language series - Section 3 - functions
Deep dive kotlin synergy (19): flow overview
Sklearn data preprocessing
2022 beautician (intermediate) new version test questions and beautician (intermediate) certificate examination
sklearn数据预处理
Nat. Comm. | use tensor cell2cell to deconvolute cell communication with environmental awareness
Joint set search: merge intervals and ask whether two numbers are in the same set
Database management tool, querious direct download
xrandr修改分辨率與刷新率
Taking two column waterfall flow as an example, how should we build an array of each column
2022 electrician (Advanced) examination papers and electrician (Advanced) examination skills
树莓派如何连接WiFi
Kingbasees plug-in KDB of Jincang database_ date_ function
Five elements of user experience
leetcode:297. Serialization and deserialization of binary tree