We can usually upload files to a server by multiple users. This can be done through TCP programming. We can do it as long as we combine the concurrency of the go language.
server first
package main import ( "net" "os" //"fmt" "io" "fmt" ) func main() { tcpaddr , _ := net.ResolveTCPAddr( "tcp" , ":34521" ) //determine IP address listener , _ := net.ListenTCP( "tcp" , tcpaddr) //listen port for { conn , _ := listener.Accept() //Request connection fmt.Println( "A client is connected" , conn.RemoteAddr()) d := make([]byte, 2048) go func(conn net.Conn) { f1, _ := os.OpenFile("e:\\205.jpg", os.O_WRONLY|os.O_CREATE, 0777) for { count , err := conn.Read(d) //Start reading after receiving the file from the client if err != nil { break } f1.Write(d[:count]) //Write the read content to the file and save it } }(conn) conn.Close() //Close the connection } } }
then the client
package main import ( "net" "io/ioutil" "fmt" ) func main(){ tcpaddr,_:=net.ResolveTCPAddr("tcp","192.168.31.168:34521")//确定服务器的地址 tcpconn,_:=net.DialTCP("tcp",nil,tcpaddr)//申请连接 defer tcpconn.Close()//完事后关闭 d,_:=ioutil.ReadFile("D:\\205.jpg") //读取本地文件 tcpconn.Write(d) //把文件写给服务器 fmt.Println(len(d)) }