1 回答
TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
關(guān)于代碼的一些注釋:
處理錯(cuò)誤。
defer connection.Close()在handleConnection. 否則,連接不會(huì)關(guān)閉,直到程序終止。將兩行代碼
handleConnection移出for循環(huán),丟棄for循環(huán)。循環(huán)沒(méi)有做任何事情。添加
defer fileWriter.Flush()以刷新寫(xiě)入器中緩沖的任何最后一位數(shù)據(jù)(但請(qǐng)參閱下一點(diǎn))。要求文件直接從連接中復(fù)制。
這是代碼:
func main() {
listen, err := net.Listen("tcp4", ":8080")
if err != nil {
log.Fatal(err)
}
defer listen.Close()
for {
connection, err := listen.Accept()
if err != nil {
log.Fatal(err)
}
go handleConnection(connection, "myfile.dat")
}
}
func handleConnection(connection net.Conn, myFile string) {
defer connection.Close()
outputFile, err := os.Create(myFile)
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
_, err = outputFile.ReadFrom(connection)
if err != nil {
log.Fatal(err)
}
}
- 1 回答
- 0 關(guān)注
- 96 瀏覽
添加回答
舉報(bào)
