go - 新行分隔的输入流写入文件
问题描述
我是 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)
}
}
解决方案
例如,您可以使用以下模式读取终止字节:
r := bufio.NewReader(conn)
for {
yourLine, err := r.ReadBytes(10)
... write your file ...
}
类似的也有r.ReadString('\n')
which would too。
推荐阅读
- android-studio - Flutter:我在将flutter_local_notification添加到依赖项后尝试构建一个项目,但失败了
- javascript - 使用 EJS 和 HTML 向已添加类的元素添加其他类?
- java - 没有 WebView 的 Android 应用程序(用 JAVA 编码)是否有可能存在 XSS 漏洞(反射或存储类型)?
- jquery - preventDefault 不适用于所有浏览器/设备
- swift - 如何在不显示弹出窗口的情况下立即打印?
- typo3 - 谷歌的站点地图有问题吗?
- angular - Angular 6 - 数据更改后绑定项不更新
- python - 为什么 Eclipse PyDev 找不到现有文件?
- flutter - 让音乐应用在后台、iOS 和 Android 中保持活力?
- security - 你能利用 emscripten 编译的 Wasm 来运行任意 JavaScript 吗?