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

标签 networking go tcp port

我正在尝试学习 net 包。我正在监听端口上的本地连接,并使用 echo -n "Server test.\n"| 将数据发送到该端口nc 本地主机 5000

但是,我在读取数据时总是遇到 EOF 错误。我检查了文档,这只应该发生 when there is no more input available ,但是我不明白为什么会发生这种情况。

这是我的代码:

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('\n')
    checkError("Error reading: ", err)

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

    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)
    }
}

最佳答案

您似乎错误地使用了 echo。标志 -e 将两个字符 \n 解释为换行符(检查 here )。

使用以下命令向服务器发送数据:

echo -e "Server test.\n" | nc localhost 5000

除此之外,您还应该修复 for 循环:

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

在您的原始代码中,您只接受一个连接。之后,for 循环会启动更多 goroutine,这些 goroutine 会尝试读取已关闭的连接(无论是否出错,第一个 handleRequest 调用会关闭连接)。

关于networking - 使用 bufio 从端口读取时出现 EOF 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47215479/

相关文章:

mysql - 视觉基本: Best way to share data/variables over network?

go - 类型、接口(interface)和指针

encoding - 我如何在 Golang 中将一个 16 位整数写入多个字节?

Android TCP 紧急消息实现

linux - 如何在 Linux 内核中找到 sk_buff 的所有者套接字?

c - 是否可以在未安装 TOR 的情况下连接到 TOR?

android - 创建TCP套接字时无法识别Android主机名

java - UDP 数据包发现不起作用

android - IP自动发现

function - 为什么这些goroutine无法打印到控制台?