Golang TCP服务器给出“拨号TCP 127.0.0.1:9999:连接:连接被拒绝”错误

时间:2020-09-09 13:16:04

标签: go

我正在从An Introduction to Programming in Go by Caleb Doxsey这本书中学习

在有关服务器的第13章中,给出了代码:

package main

import (
    "encoding/gob"
    "fmt"
    "net"
)

func server() {
    // listen on a port

    ln, err := net.Listen("tcp", ":9999")

    if err != nil {
        fmt.Println("server, Listen", err)
        return
    }

    for {
        // accept a connection
        c, err := ln.Accept()
        if err != nil {
            fmt.Println("server, Accept", err)
            continue
        }
        // handle the connection
        go handleServerConnection(c)
    }
}

func handleServerConnection(c net.Conn) {
    // receive the message
    var msg string
    err := gob.NewDecoder(c).Decode(&msg)
    if err != nil {
        fmt.Println("handleServerConnection", err)
    } else {
        fmt.Println("Received", msg)
    }

    c.Close()
}

func client() {
    // connect to the server
    c, err := net.Dial("tcp", "127.0.0.1:9999")
    if err != nil {
        fmt.Println("client, Dial", err)
        return
    }

    // send the message
    msg := "Hello World"
    fmt.Println("Sending", msg)
    err = gob.NewEncoder(c).Encode(msg)
    if err != nil {
        fmt.Println("client, NewEncoder", err)
    }

    c.Close()
}

func main() {
    go server()
    go client()
    
    var input string
    fmt.Scanln(&input)
}

运行此代码我几乎总是收到:

客户端,拨打tcp tcp 127.0.0.1:9999:连接:连接被拒绝

但是有时候我会收到:

发送Hello World

收到“ Hello World”

我还发现,如果我只运行与客户端分开运行的服务器,然后在单独的文件上运行客户端,它会按预期工作。为什么呢?

1 个答案:

答案 0 :(得分:2)

收听和拨号同时被调用,您无法预测哪个首先执行。如果Dial在Listen之前执行,那么显然还没有监听,并且会产生错误。

在启动goroutine之前,先在main中调用Listen:

slot(x, "proj4string") <- slot(y, "proj4string")
相关问题