Client:
package main
import (
"fmt"
"io"
"net"
"os"
)
func SendFile(path string, conn net.Conn) {
// Open file as read-only
f, err := os.Open(path)
if err != nil {
fmt.Println("os.Open err = ", err)
return
}
defer f.Close()
buf := make([]byte, 1024*4)
//Read file content
for {
n, err := f.Read(buf)
if err != nil {
if err == io.EOF {
fmt.Println("File sented")
} else {
fmt.Println("f.Read err = ", err)
}
return
}
if n == 0 {
fmt.Println("File sented")
return
}
conn.Write(buf[:n]) // Send content to the server
}
}
func main() {
fmt.Println("Please enter the name of the file to be passed!")
var path string
fmt.Scan(&path)
info, err := os.Stat(path)
if err != nil {
fmt.Println("os.Stat err = ", err)
return
}
//Active connection to the server
conn, err1 := net.Dial("tcp", ":8000")
if err1 != nil {
fmt.Println("net.Dial err = ", err)
return
}
defer conn.Close()
//Send the file name to receiver
var n int
n, err = conn.Write([]byte(info.Name()))
if err != nil {
fmt.Println("conn.Write err = ", err)
return
}
// Receive reply from the server
buf := make([]byte, 1024*4)
n, err = conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err = ", err)
return
}
if "ok" == string(buf[:n]) {
SendFile(path, conn)
}
}
Server:
package main
import (
"fmt"
"io"
"net"
"os"
)
func RecvFile(fileName string, conn net.Conn) {
f, err := os.Create(fileName)
if err != nil {
fmt.Println("os.Create err = ", err)
return
}
var n int
buf := make([]byte, 1024*4)
for {
n, err = conn.Read(buf) //Receive file content
if err != nil {
if err == io.EOF {
fmt.Println("File received")
} else {
fmt.Println("os.Create err = ", err)
}
return
}
f.Write(buf[:n]) //Write content to the file
}
}
func main() {
//Listen
listenner, err := net.Listen("tcp", ":8000")
if err != nil {
fmt.Println("net.Listen err = ", err)
return
}
defer listenner.Close()
conn, err1 := listenner.Accept()
defer conn.Close()
if err1 != nil {
fmt.Println("listenner.Accept err = ", err1)
return
}
buf := make([]byte, 1024)
var n int
n, err = conn.Read(buf) //Read the file name sent by the client
if err != nil {
fmt.Println("conn.Read err = ", err)
return
}
fileName := string(buf[:n])
conn.Write([]byte("ok"))
//Receive file content
RecvFile(fileName, conn)
}