使用go语言实现传输文件
发送方(客户端)
package main
import (
"fmt"
"io"
"net"
"os"
)
func main(){
fmt.Println("请输入需要传输的文件:")
var path string
fmt.Scan(&path)
info,err := os.Stat(path)
if err != nil{
fmt.Println("os.Stat err:",err)
return
}
conn,err1 := net.Dial("tcp","127.0.0.1:8080")
if err1 != nil{
fmt.Println("net.Dail err1:",err1)
return
}
defer conn.Close()
_ , err2 := conn.Write([]byte(info.Name()))
if err2 != nil{
fmt.Println("conn.Write err",err2)
return
}
buf := make([]byte,1024)
n,err3 := conn.Write(buf)
if err != nil{
fmt.Println("conn.Write err:",err3)
}
if "ok" == string(buf[:n]){
SendFile(path,conn)
}
}
func SendFile(path string,conn net.Conn){
f ,err4 := os.Open(path)
if err4 != nil{
fmt.Println("os.Open err:",err4)
return
}
defer f.Close()
buf := make([]byte,1024*4)
for {
n,err5 := f.Read(buf)
if err5 != nil {
if err5 == io.EOF {
fmt.Println("文件发送完毕")
}else {
fmt.Println("f.Read err:",err5)
}
return
}
conn.Write(buf[:n])
}
}
接收方
package main
import (
"fmt"
"io"
"net"
"os"
)
func main(){
listener,err := net.Listen("tcp","127.0.0.1:8080")
if err != nil{
fmt.Println("net.Listen err",err)
return
}
defer listener.Close()
conn,err1 := listener.Accept()
if err1 != nil {
fmt.Println("listener.Accept err:",err1)
return
}
defer conn.Close()
buf := make([]byte,1024)
n,err2 := conn.Read(buf)
if err2 != nil {
fmt.Println("conn.Read err",err2)
return
}
fileName := string(buf[:n])
conn.Write([]byte("ok"))
RecvFile(fileName,conn)
}
func RecvFile(fileName string,conn net.Conn) {
f,err3 := os.Create(fileName)
if err3 != nil{
fmt.Println("os.Create err:",err3)
return
}
buf := make([]byte,1024*4)
for {
n,err4 := conn.Read(buf)
if err4 != nil {
if err4 == io.EOF{
fmt.Println("文件接受完毕")
}else {
fmt.Println("conn.Read err",err4)
}
return
}
if n == 0 {
fmt.Println("n == 0,文件接受完毕")
return
}
f.Write(buf[:n])
}
}