【问题标题】:New line delimited input stream written to file新行分隔的输入流写入文件
【发布时间】: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


【解决方案1】:

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

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

类似的还有r.ReadString('\n')。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2012-04-02
    相关资源
    最近更新 更多