当前位置:网站首页>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)
}
边栏推荐
- [文献阅读] Sparsity in Deep Learning: Pruning and growth for efficient inference and training in NN
- Leecode swipe questions and record LCP 18 breakfast combination
- js实现在可视区内,文字图片动画效果
- [set theory] set concept and relationship (set family | set family examples | multiple sets)
- Xrandr modifier la résolution et le taux de rafraîchissement
- 2022-07-02: what is the output of the following go language code? A: Compilation error; B:Panic; C:NaN。 package main import “fmt“ func main() { var a =
- 2022-02-12 (338. Bit count)
- 怎么用Kotlin去提高生产力:Kotlin Tips
- How to process the current cell with a custom formula in conditional format- How to address the current cell in conditional format custom formula?
- Classes in TS
猜你喜欢

Feature_selection

CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes

Deep dive kotlin synergy (19): flow overview

Busycal latest Chinese version

The time has come for the domestic PC system to complete the closed loop and replace the American software and hardware system

X-ray normal based contour rendering

Five elements of user experience

Use the benchmarksql tool to perform a data prompt on kingbases. The jdbc driver cannot be found

CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强

China Mobile Internet of things oneos and onenet were selected in the list of 2021 Internet of things demonstration projects
随机推荐
Smart contract security audit company selection analysis and audit report resources download - domestic article
智能合约安全审计公司选型分析和审计报告资源下载---国内篇
多板块轮动策略编写技巧----策略编写学习教材
[set theory] set identities (idempotent law | exchange law | combination law | distribution rate | De Morgan law | absorption rate | zero law | identity | exclusion law | contradiction law | complemen
Square root of X
Dismantle a 100000 yuan BYD "Yuan". Come and see what components are in it.
RSRS指标择时及大小盘轮动
How do you use lodash linking function- How do you chain functions using lodash?
JS realizes the animation effect of text and pictures in the visual area
怎么用Kotlin去提高生产力:Kotlin Tips
Deep dive kotlin synergy (20): build flow
RSRS index timing and large and small disc rotation
金仓KFS数据双向同步场景部署
P35-P41 fourth_ context
Xrandr modify resolution and refresh rate
What are the Bluetooth headsets with good sound quality in 2022? Inventory of four high-quality Bluetooth headsets
跨境电商多商户系统怎么选
解决bp中文乱码
[fxcg] inflation differences will still lead to the differentiation of monetary policies in various countries
[untitled] 2022 safety production supervisor examination question bank and simulated safety production supervisor examination questions