我用 Go 编写了一个 UDP 服务器和客户端。当服务器运行时port 1200,我没有看到任何错误消息,当客户端尝试连接到同一台机器上的端口 1200 时,我也没有看到任何错误(OS X 10.9.1)
服务器没有在无限循环中打印“SOS ...”,即客户端正在写入的消息。
虽然客户端能够向服务器发送消息,但是服务器读取的是 0 字节。
服务器代码
package main
import ( "net" "fmt" "time" )
func main() {
port := "127.0.0.1:1200"
udpAddress, err := net.ResolveUDPAddr("udp4",port)
if err != nil {
fmt.Println("error resolving UDP address on ", port)
fmt.Println(err)
return
}
conn ,err := net.ListenUDP("udp",udpAddress)
if err != nil {
fmt.Println("error listening on UDP port ", port)
fmt.Println(err)
return
}
defer conn.Close()
var buf []byte
for {
time.Sleep(100 * time.Millisecond)
n,address, err := conn.ReadFromUDP(buf)
if err != nil {
fmt.Println("error reading data from connection")
fmt.Println(err)
return
}
if address != nil {
fmt.Println("got message from ", address, " with n = ", n)
if n > 0 {
fmt.Println("from address", address, "got message:", string(buf[0:n]), n)
}
}
}
}
客户端代码,运行在同一台服务器上,使用命令go run udp-client.go :1200或go run udp-client.go 127.0.0.1:1200
package main
import (
"fmt"
"net"
"os"
"time"
)
func main() {
if len(os.Args) != 2{
fmt.Fprintf(os.Stderr, "Usage:%s host:port", os.Args[0])
os.Exit(1)
}
service := os.Args[1]
fmt.Println("Connecting to server at ", service)
conn, err := net.Dial("udp",service)
if err != nil {
fmt.Println("Could not resolve udp address or connect to it on " , service)
fmt.Println(err)
return
}
犯罪嫌疑人X
相关分类