用Golang编写的UDP客户端无法从服务器接收消息 [英] UDP-Client written in Golang fails to receive Message from Server
问题描述
我写了一个Java客户端,它将消息发送到广播地址.
I have written a Java Client, which sends a message to the broadcast address.
我还写了一个Java Server,它接受所有已发送的消息并将消息发送回客户端.
I have also written a Java Server, which accepts all sent messages and sends the message back to the client.
现在,我想尝试在Go中做完全相同的事情,只是为了获得一些经验.服务器工作正常,正在接收消息并响应Java客户端.
Now I wanted to try to do exactly the same in Go, just for gaining some experience. The server works fine and is receiving a message and responding to the Java client.
但是我的Go Client仅向Go/Java服务器发送一条消息,但没有收到任何返回的消息.据wireshark称,该消息被发送回正确的IP和端口,但显然该端口不可达.
But my Go Client is only sending a message to the Go/Java server but does not receive any message back. According to wireshark the message is sent back to the right IP and Port, but apparently the port is unreachable.
我的代码如下:转到服务器:
My Code is as follows: Go Server:
package main
import (
"fmt"
"log"
"net"
)
func main() {
//Resolving address
udpAddr, err := net.ResolveUDPAddr("udp4", "0.0.0.0:8888")
if err != nil {
log.Println("Error: ", err)
}
// Build listining connections
conn, err := net.ListenUDP("udp", udpAddr)
defer conn.Close()
if err != nil {
log.Println("Error: ", err)
}
// Interacting with one client at a time
for {
fmt.Println(">>>Ready to receive broadcast packets!")
// Receiving a message
recvBuff := make([]byte, 15000)
_, rmAddr, err := conn.ReadFromUDP(recvBuff)
if err != nil {
panic(err)
}
fmt.Println(">>>Discovery packet received from: " + rmAddr.String())
fmt.Println(">>>Packet received; data: " + string(recvBuff))
// Sending the same message back to current client
conn.WriteToUDP(recvBuff, rmAddr)
fmt.Println(">>>Sent packet to: " + rmAddr.String())
}}
转到客户端:
package main
import (
"fmt"
"log"
"net"
"os"
)
func main() {
service := "158.129.239.255:8888"
// Resolving Address
RemoteAddr, err := net.ResolveUDPAddr("udp", service)
// Make a connection
conn, err := net.DialUDP("udp", nil, RemoteAddr)
defer conn.Close()
// Exit if some error occured
if err != nil {
log.Fatal(err)
os.Exit(1)
}
// write a message to server
message := []byte("message")
_, err = conn.Write(message)
fmt.Println(">>> Request packet sent to: 158.129.239.255 (DEFAULT)")
if err != nil {
log.Println(err)
}
// Receive response from server
buf := make([]byte, 15000)
amountByte, remAddr, err := conn.ReadFromUDP(buf)
if err != nil {
log.Println(err)
} else {
fmt.Println(amountByte, "bytes received from", remAddr)
}
}
Java客户端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BroadcastUDPClient {
public static void main(String[] args) {
// Find the server using UDP broadcast
try {
//Open a random port to send the package
DatagramSocket sendSD = new DatagramSocket();
sendSD.setBroadcast(true);
byte[] sendData = "message".getBytes();
//Try the 255.255.255.255 first
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("158.129.239.255"), 8888);
sendSD.send(sendPacket);
System.out.println(">>> Request packet sent to: 158.129.239.255 (DEFAULT)");
} catch (Exception e) {
}
//Wait for a response
byte[] recvBuf = new byte[15000];
DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
sendSD.receive(receivePacket);
//We have a response
System.out.println(">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress());
String message = new String(receivePacket.getData()).trim();
System.out.println(">>> Message Body: " + message);
//Close the port!
sendSD.close();
} catch (IOException ex) {
Logger.getLogger(BroadcastUDPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我的Go Client我怎么了?
What am I doing wrong with my Go Client?
推荐答案
Even if you're you're only going to be sending UDP packets from the connection, you generally want to use ListenUDP
to create the connection, and use the ReadFromUDP
and WriteToUDP
methods.
使用 DialUDP
时,它将创建一个连接的" UDP套接字,该套接字具有隐式的远程端点,该端点将过滤传入的数据包.从Linux connect
手册页:
When you use DialUDP
, it creates a "connected" UDP socket, with an implicit remote endpoint, which will filter incoming packets. From the Linux connect
man page:
如果套接字sockfd的类型为SOCK_DGRAM,则addr是默认情况下向其发送数据报的地址,也是唯一从其接收数据报的地址.
If the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received.
这篇关于用Golang编写的UDP客户端无法从服务器接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!