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

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

问题描述



我在互联网上找到的例子向我展示了如何在Go语言中使用UDP套接字进行客户端/服务器通信。发送数据到服务器,但他们没有教会如何将它们发送回客户端。



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



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

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

我发送了一个字符串和服务器的本地地址,所以它可以打印字符串并发送OK消息。我使用gob:

$ $ p $ code enc:= gob.NewEncoder(con)
enc.Encode(Data { test,con.LocalAddr()。String()})

My Data struct看起来像这样:

 类型数据结构{
消息字符串
地址字符串
}

我的服务器监听4444端口并正确解码Gob,但是如何发回OK消息?我使用客户端地址(在服务器的.go文件中):

  con,err:= net。拨号(udp,data.Addr)

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

 写入udp 127.0.0.1:35290:连接被拒绝

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



Obs .:我知道有ReadFromUDP,所以我可以阅读包。我应该阅读它,发现客户的地址,并将数据发送给GOB,这样它可以解码它? 解决方案

通过UDP进行客户端/服务器通信的样本。 sendResponse例程用于将响应发送回客户端。



udpclient.go



<$
$ f










$ b $ $ b func main(){
p:= make([] byte,2048)
conn,err:= net.Dial(udp,127.0.0.1:1234)
如果err!= nil {
fmt.Printf(某个错误%v,err)
返回
}
fmt.Fprintf(conn,Hi UDP Server, )
_,err = bufio.NewReader(conn).Read(p)
if err == nil {
fmt.Printf(%s\\\
, p)
} else {
fmt.Printf(有些错误%v \ n,err)
}
conn.Close()
}

udpserver.go

 包主
导入(
fmt




func sendResponse(conn * net.UDPConn,addr * net.UDPAddr){
_,err:= conn.WriteToUDP([] byte( 从服务器:你好,我得到了你的消息),addr)
if err!= nil {
fmt.Printf(Could not send response%v,err)
}


$ b func main(){
p:= make([] byte,2048)
addr:= net.UDPAddr {
端口:1234,
IP:net.ParseIP(127.0.0.1),
}
ser,err:= net.ListenUDP(udp,& addr)
如果err!= nil {
fmt.Printf(有些错误%v \ n,err)
返回
}
用于{
_,remoteaddr ,err:= ser.ReadFromUDP(p)
fmt.Printf(从%v%s \\\
读取消息,remoteaddr,p)
if err!= nil {
fmt.Printf(Some error%v,err)
continue
}
go sendResponse(ser,remoteaddr)
}
}


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

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:

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

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

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
}

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

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.: 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?

解决方案

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\n", p)
    } else {
        fmt.Printf("Some error %v\n", 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 mesage "), 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\n", err)
        return
    }
    for {
        _,remoteaddr,err := ser.ReadFromUDP(p)
        fmt.Printf("Read a message from %v %s \n", remoteaddr, p)
        if err !=  nil {
            fmt.Printf("Some error  %v", err)
            continue
        }
        go sendResponse(ser, remoteaddr)
    }
}

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

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