当前位置:网站首页>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)
}
边栏推荐
- 服务器无法远程连接原因分析
- [fxcg] market analysis today
- Classes in TS
- Interface in TS
- 国产PC系统完成闭环,替代美国软硬件体系的时刻已经到来
- Bugku CTF daily question baby_ flag. txt
- The latest activation free version of Omni toolbox
- Basic types of data in TS
- Design and implementation of JSP logistics center storage information management system
- 怎么用Kotlin去提高生产力:Kotlin Tips
猜你喜欢

Supervised pre training! Another exploration of text generation!

Deep dive kotlin synergy (19): flow overview
![[fxcg] market analysis today](/img/ac/294368e3496a5b808b38833053ee81.jpg)
[fxcg] market analysis today

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 =

竞品分析撰写
![[NLP]—sparse neural network最新工作简述](/img/65/35ae0137f4030bdb2b0ab9acd85e16.png)
[NLP]—sparse neural network最新工作简述

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

Feature_selection

Basic use of continuous integration server Jenkins

Mila、渥太华大学 | 用SE(3)不变去噪距离匹配进行分子几何预训练
随机推荐
使用BENCHMARKSQL工具对KingbaseES预热数据时执行:select sys_prewarm(‘NDX_OORDER_2 ‘)报错
Basic syntax of class
[set theory] set concept and relationship (set represents | number set | set relationship | contains | equality | set relationship property)
Kingbasees plug-in KDB of Jincang database_ database_ link
The 10th China Cloud Computing Conference · China Station: looking forward to the trend of science and technology in the next decade
MySQL create table
Factor stock selection scoring model
[nlp] - brief introduction to the latest work of spark neural network
Busycal latest Chinese version
Basic use of continuous integration server Jenkins
Causal AI, a new paradigm for industrial upgrading of the next generation of credible AI?
使用BENCHMARKSQL工具对kingbasees并发测试时kill掉主进程成功后存在子线程未及时关闭
[set theory] set operation (Union | intersection | disjoint | relative complement | symmetric difference | absolute complement | generalized union | generalized intersection | set operation priority)
服务器无法远程连接原因分析
有监督预训练!文本生成又一探索!
Database management tool, querious direct download
xrandr修改分辨率與刷新率
MySQL field userid comma separated save by userid query
sd卡数据损坏怎么回事,sd卡数据损坏怎么恢复
金仓KFS数据双向同步场景部署