doufen9815 2014-09-25 00:39
浏览 67
已采纳

在Go中写入客户端UDP套接字

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?

  • 写回答

1条回答 默认 最新

  • duanjianao0592 2014-09-25 06:43
    关注

    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 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
    ", 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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题