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.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看