上传端
send.go
package main
import (
"fmt"
"io"
"net"
"os"
)
func main() {
fmt.Println("请输入要传输的文件")
var filePath string
fmt.Scan(&filePath)
info,err := os.Stat(filePath)
if err !=nil{
fmt.Println("获取文件属性失败")
}
conn,err := net.Dial("tcp","127.0.0.1:8000")
if err !=nil{
fmt.Println("连接服务器出错")
}
defer conn.Close()
_,err = conn.Write([]byte(info.Name()))
if err!=nil{
fmt.Println("发送文件名出错")
}
buff := make([]byte,1024)
n,err:= conn.Read(buff)
if err !=nil {
fmt.Println(err)
}
str := string(buff[:n])
if "ok" !=str{
fmt.Println("接收文件错误")
}
sendFile(filePath ,conn)
}
func sendFile(filePath string,conn net.Conn) {
buff := make([]byte,1024)
fileHandle,err := os.Open(filePath)//打开文件
if err!=nil{
if err == io.EOF{
fmt.Println("发送文件完毕")
}else{
fmt.Println("打开文件失败")
}
return
}
defer fileHandle.Close() //关闭文件
n,err := fileHandle.Read(buff)//读取文件内容
if err!=nil{
fmt.Println("读取文件失败")
return
}
conn.Write(buff[:n]);
}
接收端(服务器端)recive.go
package main
import (
"fmt"
"io"
"net"
"os"
)
func main() {
lisener,err := net.Listen("tcp","127.0.0.1:8000")
if err !=nil{
fmt.Println("监听失败")
}
defer lisener.Close()
conn,err :=lisener.Accept()
defer conn.Close()
if err !=nil{
fmt.Println("连接失败")
}
buffer := make([]byte,1024)
n,err :=conn.Read(buffer)
if err!=nil{
fmt.Println("获取内容失败")
}
fileNme :=string(buffer[:n])
_,err = conn.Write([]byte("ok"))
if err !=nil{
fmt.Println("发送内容失败")
}
reciveFile(fileNme,conn)
}
func reciveFile(filName string,conn net.Conn){
file,err := os.Create(filName)
if err!=err{
fmt.Println(err)
return
}
buff := make([]byte,1024)
for{
n,err := conn.Read(buff)
if err!=nil{
if err == io.EOF{
fmt.Println("文件接收完毕")
return
}else {
fmt.Println("读取内容失败")
}
}
if n==0{
fmt.Println("文件传输完毕")
return
}
_,err =file.Write([]byte(buff[:n]))
if err!=nil{
fmt.Println("写入文件失败")
}
}
}