dongli2000 2018-10-26 00:28
浏览 33
已采纳

在获得用户输入之前,TCP连接已关闭

I have setup a server to wait for a TCP connection and read an input from the user:

func main() {
  err := godotenv.Load()
  if err != nil {
    log.Fatal(err)
  }

  server, err := net.Listen("tcp", ":"+os.Getenv("PORT"))

  if err != nil {
    log.Fatal(err)
  }

  log.Println("HTTP Server Listening on port :", os.Getenv("PORT"))
  defer server.Close()

  for {
    conn, err := server.Accept()
    if err != nil {
      log.Fatal(err)
    }
    go handleConn(conn)
  }
}

The issue I am having is in my handleConn function. I want to kick off reading the input into a goroutine because there will be additional data processing. However, when I connect to my server (nc localhost 9000), my connection gets dropped immediately.

func handleConn(conn net.Conn) {
  defer conn.Close()
  io.WriteString(conn, "Enter a transaction:")

  scanner := bufio.NewScanner(conn)

  go func() {
    for scanner.Scan() {
      log.Println("User entered: ")
      log.Println(scanner.Text())
    }

  }()
}

I see the message Enter a transaction:, but I am not able to input anything because my connection is immediately terminated and I am kicked back to my bash terminal. What am I doing wrong here?

Edit: I am following this tutorial - https://github.com/mycoralhealth/blockchain-tutorial/blob/master/networking/main.go.

I have tried moving scanner.Scan() outside the goroutine and this works, but the code example here has it within the goroutine and his example works. Why is this the case?

  • 写回答

1条回答 默认 最新

  • duan198409 2018-10-26 00:49
    关注

    Since you're spawning a goroutine in your handleConn func, it doesn't need to wait for anything to return, so the deferred conn.Close() runs and closes the connection. You might need to run scanner.Scan() out of the goroutine so that it blocks waiting for input.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型