首页 > 解决方案 > 新行分隔的输入流写入文件

问题描述

我是 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

解决方案


例如,您可以使用以下模式读取终止字节:

    r := bufio.NewReader(conn)
    for {
        yourLine, err := r.ReadBytes(10)
        ... write your file ...
    }

类似的也有r.ReadString('\n')which would too。


推荐阅读