UDP服务器/客户端在Go中无法读取数据

huangapple go评论87阅读模式
英文:

UDP server / client in Go not reading data

问题

我已经用Go语言编写了一个UDP服务器和客户端。当服务器在端口1200上运行时,我没有看到任何错误消息,当客户端尝试连接到同一台机器上的端口1200时,也没有看到任何错误。

服务器没有打印"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 :1200go 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
    }

    fmt.Println("Connected to server at ", service)

    defer conn.Close()

    fmt.Println("About to write to connection")

    for {

        time.Sleep(1000 * time.Millisecond)
        n, err := conn.Write([]byte("SOS ... \n"))
        if err != nil {
            fmt.Println("error writing data to server", service)
            fmt.Println(err)
            return
        }

        if n > 0 {
            fmt.Println("Wrote ", n, " bytes to server at ", service)
        }
    }

}

希望对你有帮助!

英文:

I have written a UDP server and client in Go. I am not seeing any error messages when the server is running on port 1200, I also do not see any errors when client is trying to connect to port 1200 on the same machine (OS X 10.9.1)

The server is not printing "SOS...", that is the message the client is writing, in a infinite loop.

The client is able to send a message to the server though, however what the server is reading is 0 bytes.

Server Code

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

}

client code, running on same server, with command go run udp-client.go :1200 or 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
        }

        fmt.Println("Connected to server at ", service)

        defer conn.Close()

        fmt.Println("About to write to connection")

        for {

                time.Sleep(1000*time.Millisecond)
                n, err := conn.Write([]byte("SOS ... \n"))
                if err != nil {
                        fmt.Println("error writing data to server", service)
                        fmt.Println(err)
                        return
                }

                if n > 0 {
                        fmt.Println("Wrote ",n, " bytes to server at ", service)
                }
        }

}

答案1

得分: 8

UDPConn.ReadFromUDP 方法读取数据并将其放入您提供的切片中。
在您的情况下,该切片为 nil。因此,您的缓冲区不提供足够的空间来存储数据。
您可以通过更改服务器代码中的一行来解决此问题:

var buf []byte = make([]byte, 1500)

缓冲区大小应该根据您的网络协议进行选择。或者您可以创建一个 64k 的缓冲区,以便可以接收最大大小的 UDP 数据包。不过,这似乎有点浪费 UDP服务器/客户端在Go中无法读取数据

英文:

The UDPConn.ReadFromUDP method reads data and puts it into the slice you provided.
In your case this slice is nil. Therefore your buffer does not provide enough space for data.
You can fix this by changing one line in the server code:

var buf []byte = make([]byte, 1500)

The buffer size should probably be chosen to fit your network protocol. Or you create a 64k buffer so that you can receive maximum sized udp packets. This however seems a bit wastefull UDP服务器/客户端在Go中无法读取数据

huangapple
  • 本文由 发表于 2013年12月22日 23:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/20730891.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定