簡單的檔案傳輸
阿新 • • 發佈:2018-12-12
package main
import (
"net"
"fmt"
"log"
"time"
"os"
"bufio"
"flag"
"strconv"
)
func writeFile(path string,write* bufio.Writer ) {
pFile,error:=os.OpenFile(path, os.O_RDONLY, 0666)
defer pFile.Close()
if error!=nil {
fmt.Println(error)
return
}
read:=bufio.NewReader(pFile)
bytes:= make ([]byte,1000)
for {
n,error:=read.Read(bytes)
if error!=nil {
break
}
bytes = bytes[:n]
write.Write(bytes)
}
write.Flush()
}
//啟動服務端
func startServer() {
addr:="0.0.0.0:8888"
listener,error:=net.Listen("tcp",addr)
if error!=nil {
fmt.Println(error)
return
}
defer listener.Close()
for {
fmt.Println("服務端等待接收檔案。。。")
conn,err:=listener.Accept()
if err !=nil{
log.Fatal(err)
}
go func() {
t:=time.Now()
pathWrite:="./"+ strconv.FormatInt(t.Unix(),10) +".new" //time.Now().Format("2006-01-02-15-04-05")
wPFile,error2:= os.OpenFile(pathWrite,os.O_CREATE|os.O_WRONLY,0666)
defer wPFile.Close()
if error2 !=nil{
fmt.Println(error)
return
}
write:=bufio.NewWriter(wPFile)
//接收客戶端發來的資料
for{
bytes:=make([]byte,1024)
n,err2:=conn.Read(bytes)
if err2 != nil {
fmt.Println(err2)
fmt.Println("接收檔案地址為 : ",pathWrite)
break
}
write.Write(bytes[:n])
write.Flush()
}
}()
}
}
//啟動客戶端
func startClient(path,addr string) {
conn,err:=net.Dial("tcp",addr)
if err!=nil{
log.Fatal(err)
}
defer conn.Close()
fmt.Println(conn.RemoteAddr().String())
write:= bufio.NewWriter(conn)
//向服務端寫入資料
writeFile(path,write)
time.Sleep(time.Second)
}
func main() {
f := flag.String("f", "nil", "檔案路徑")
h :=flag.String("h", "nil", "對方主機")
s :=flag.String("s", "nil", "伺服器啟動")
flag.Parse()
path:=*f
addr:=*h
index:=0
if "nil" != path {
index++
}
if "nil" != addr {
index++
}
if index == 2{
startClient(path,addr)
}else {
if "start" == *s {
startServer()
}else {
fmt.Println("啟動客戶端 eg: ./main -h ip:8888 -f 檔案\n"+
"啟動服務端 eg: ./main -s start")
}
}
}