In chapter 13 about servers 我们得到了代码:
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)
}
运行这段代码我几乎总是收到:
客户端,Dial dial tcp 127.0.0.1:9999:连接:连接被拒绝
但有时我会收到:
发送 Hello World
收到Hello World
我还发现,如果我只运行与客户端分开运行服务器,然后在单独的文件上运行客户端,它会按预期工作。这是为什么呢?