duangu8264 2017-11-10 04:02
浏览 332

使用bufio从端口读取时出现EOF错误

I am trying to learn the net package. I am listening for local connections on a port, and sending data to that port using echo -n "Server test. " | nc localhost 5000.

I always get an EOF error when reading the data, however. I checked the docs and this is only supposed to happen when there is no more input available, however I don't understand why this is happening here.

This is my code:

package main

import (
    "bufio"
    "fmt"
    "net"
    "os"
)

// Connection details
type connection struct {
    host    string
    port    string
    network string
}

// Initialise a Listener on a given port
// Pass handling into seperate goroutine
func main() {
    localConn := connection{
            host:    "", // Localhost
            port:    "5000",
            network: "tcp",
    }

    listener, err := net.Listen(localConn.network, localConn.host+":"+localConn.port)
    checkError("Error listening: ", err)

    conn, err := listener.Accept()
    for {
            checkError("Error accepting: ", err)
            go handleRequest(conn)
    }
}

// Delegate handling of requests
func handleRequest(conn net.Conn) {
    // Read message up until newline delimiter
    message, err := bufio.NewReader(conn).ReadString('
')
    checkError("Error reading: ", err)

    fmt.Println("Message recieved: ", string(message))
    conn.Write([]byte("Recieved message: " + string(message) + "
"))

    conn.Close()
}

// Check if an error exists
// If so, print and exit program. (Not super robust!)
func checkError(message string, err error) {
    if err != nil {
            fmt.Println(message, err.Error())
            os.Exit(1)
    }
}
  • 写回答

2条回答 默认 最新

  • douzhongjian0752 2017-11-10 05:12
    关注

    One problem is on these lines:

    conn, err := listener.Accept()
    for {
            checkError("Error accepting: ", err)
            go handleRequest(conn)
    }
    

    The application starts goroutines in a loop to read the single connection. The first goroutine to read the connection is successful. The subsequent goroutines report an error.

    Change the code to:

    for {
            conn, err := listener.Accept()
            checkError("Error accepting: ", err)
            go handleRequest(conn)
    }
    

    The client is not sending a newline as expected by the server. Use this command to send the message:

    echo "Server test." | nc localhost 5000
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?