在 Go 中写入客户端 UDP 套接字 [英] Write to Client UDP Socket in Go

查看:23
本文介绍了在 Go 中写入客户端 UDP 套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为使用 Go 语言的 UDP 套接字进行客户端/服务器通信寻找一个好的解决方案.

I'm looking for a good solution for a client/server communication with UDP sockets in Go language.

我在 Internet 上找到的示例向我展示了如何将数据发送到服务器,但没有教如何将它们发送回客户端.

The examples I found on the Internet show me how to send data to the server, but they do not teach how to send them back to the client.

为了演示,我的程序执行以下操作:

To demonstrate, my program does the following:

我的客户端程序在 4444 端口上创建一个套接字,如下所示:

My client program creates a socket on the 4444 port, like this:

con, err := net.Dial("udp", "127.0.0.1:4444")

我向服务器发送了一个字符串和本地地址,因此它可以打印该字符串并发送一个 OK 消息.我为此使用 gob:

I sent a string and the local address to the server, so it could print the string and send an OK message. I am using gob for this:

enc := gob.NewEncoder(con)
enc.Encode(Data{"test", con.LocalAddr().String()})

我的数据结构如下所示:

My Data struct looks like this:

type Data struct{
    Msg string
    Addr string
}

我的服务器侦听 4444 端口并正确解码 Gob,但我怎样才能将 OK 消息发回?我正在使用客户端地址来执行此操作(在服务器 .go 文件上):

My server listens to the 4444 port and decodes the Gob correctly, but how can I send the OK message back? I'm using the client address to do so (on the server .go file):

con, err := net.Dial("udp", data.Addr)

然后,我得到一个错误代码:

Then, I get an error code:

write udp 127.0.0.1:35290: connection refused

当客户端尝试连接到服务器的端口 4444 时,客户端会创建一个带有随机数(在本例中为 35290)的端口,以便它们可以通信.我知道我不应该将客户端的地址传递给服务器,但是 conn.RemoteAddress() 不起作用.发现客户地址的解决方案将不胜感激.

When the client tries to connect to the Server's port 4444, the client creates a port with a random number (in this case, 35290) so they can communicate. I know I shouldn't be passing the client's address to the server, but conn.RemoteAddress() does not work. A solution that discovers the client's address would be most appreciated.

Obs.:我知道有 ReadFromUDP,所以我可以读取包.我应该阅读它,发现客户端的地址,然后将数据发送到 Gob 以便它可以解码吗?

Obs.: I know there is ReadFromUDP, so I can read the package. Should I read it, discover the client's address, and send the data to Gob so it can decode it?

推荐答案

检查以下示例以了解通过 UDP 进行的客户端/服务器通信.sendResponse 例程用于将响应发送回客户端.

Check the below samples for client/server communication over UDP. The sendResponse routine is for sending response back to client.

udpclient.go

package main
import (
    "fmt"
    "net"
    "bufio"
)

func main() {
    p :=  make([]byte, 2048)
    conn, err := net.Dial("udp", "127.0.0.1:1234")
    if err != nil {
        fmt.Printf("Some error %v", err)
        return
    }
    fmt.Fprintf(conn, "Hi UDP Server, How are you doing?")
    _, err = bufio.NewReader(conn).Read(p)
    if err == nil {
        fmt.Printf("%s
", p)
    } else {
        fmt.Printf("Some error %v
", err)
    }
    conn.Close()
}

udpserver.go

package main
import (
    "fmt" 
    "net"  
)


func sendResponse(conn *net.UDPConn, addr *net.UDPAddr) {
    _,err := conn.WriteToUDP([]byte("From server: Hello I got your message "), addr)
    if err != nil {
        fmt.Printf("Couldn't send response %v", err)
    }
}


func main() {
    p := make([]byte, 2048)
    addr := net.UDPAddr{
        Port: 1234,
        IP: net.ParseIP("127.0.0.1"),
    }
    ser, err := net.ListenUDP("udp", &addr)
    if err != nil {
        fmt.Printf("Some error %v
", err)
        return
    }
    for {
        _,remoteaddr,err := ser.ReadFromUDP(p)
        fmt.Printf("Read a message from %v %s 
", remoteaddr, p)
        if err !=  nil {
            fmt.Printf("Some error  %v", err)
            continue
        }
        go sendResponse(ser, remoteaddr)
    }
}

这篇关于在 Go 中写入客户端 UDP 套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆