当前位置:网站首页>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)
}
边栏推荐
- Mila、渥太华大学 | 用SE(3)不变去噪距离匹配进行分子几何预训练
- Export of zip file
- 使用BENCHMARKSQL工具对kingbaseES执行灌数据提示无法找到JDBC driver
- Mongodb slow query optimization analysis strategy
- Xrandr modifier la résolution et le taux de rafraîchissement
- Design and implementation of kubelet garbage collection mechanism to protect nodes from being preempted by containers image GC high threshold
- 金仓数据库KingbaseES 插件kdb_exists_expand
- [mathematical logic] predicate logic (toe normal form | toe normal form conversion method | basic equivalence of predicate logic | name changing rules | predicate logic reasoning law)
- js实现在可视区内,文字图片动画效果
- mysql字段userid逗号分开保存按userid查询
猜你喜欢

Two points -leetcode-540 A single element in an ordered array

拆一辆十万元的比亚迪“元”,快来看看里面的有哪些元器件。

redis 持久化原理

Joint search set: the number of points in connected blocks (the number of points in a set)

Daily question - ugly number

JS实现图片懒加载

Feature_selection

使用BENCHMARKSQL工具对KingbaseES预热数据时执行:select sys_prewarm(‘NDX_OORDER_2 ‘)报错

leetcode:297. Serialization and deserialization of binary tree

CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes
随机推荐
FFMpeg example
mysql字段userid逗号分开保存按userid查询
使用BENCHMARKSQL工具对KingbaseES预热数据时执行:select sys_prewarm(‘NDX_OORDER_2 ‘)报错
解决bp中文乱码
How to use kotlin to improve productivity: kotlin tips
Web - Information Collection
Kingbasees plug-in KDB of Jincang database_ database_ link
Dive into deep learning - 2.1 data operation & Exercise
拆一辆十万元的比亚迪“元”,快来看看里面的有哪些元器件。
Supervised pre training! Another exploration of text generation!
服务器无法远程连接原因分析
Export of zip file
深潜Kotlin协程(二十):构建 Flow
xrandr修改分辨率與刷新率
金仓数据库KingbaseES 插件kdb_exists_expand
CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强
Joint set search: merge intervals and ask whether two numbers are in the same set
How to process the current cell with a custom formula in conditional format- How to address the current cell in conditional format custom formula?
220214c language learning diary
类的基础语法