【发布时间】:2020-05-21 05:56:55
【问题描述】:
我是 GoLang 的新手,我可能正在尝试做一些不可能的事情。任何帮助,将不胜感激。
我的问题是如何创建一个服务器来获取由换行符分隔的消息,并且一旦收到换行符,我想将缓冲区的内容写入唯一文件?
我的服务器逻辑看起来很标准。下面是我尝试执行上述任务的 handleConnection 函数:
func handleConnection(conn net.Conn) {
// closes the connection on exit
defer func() {
if err := conn.Close(); err != nil {
log.Println("error closing connection: ", err)
}
}()
// create a buffer for the incoming data
buf := make([]byte, 4096)
// read the incoming connection into the buffer
size, err := conn.Read(buf)
if err != nil {
fmt.Println("error reading: ", err.Error)
}
s := string(buf[:size])
fmt.Println(s)
// set the files permissions
perm := os.FileMode(0777)
// writes to the file and generates an err value
err := ioutil.WriteFile("adt_output.txt", buf[:size], perm)
// if err is not nol show the error
if err != nil {
log.Fatal(err)
}
}
【问题讨论】:
-
您的问题/问题是什么?
-
为清晰起见已更新
标签: go