我已经创建了这个SpringBoot应用程序,通过用户数据报协议探索与Java的网络通信。我在Eclipse Java EE IDE for Web Developers中运行应用程序,版本:Oxygen.1a版本(4.7.1a)
这里是主要课程:
filter
这里创建了一个客户端UDP类来测试服务器
@Override
public void run(String... args) throws Exception {
socket = new DatagramSocket(UDP_PORT);
byte[] receiveData = new byte[BUFFER_SIZE];
byte[] sendData = new byte[BUFFER_SIZE];
LOG.info("UDP server init...");
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0, receivePacket.getLength() );
LOG.info("recived [" + sentence + "] from " + receivePacket.getAddress());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(receiveData, receiveData.length, IPAddress, receivePacket.getPort());
socket.send (sendPacket);
}
}
在我的电脑上工作正常,然后我在服务器上部署UDPServer,我使用ipconfig获取了ip
IPv4地址。 。 。 。 。 。 。 。 。 。 。 :214.146.86.201
然后我更换" localhost"对于" 214.146.86.201",但我没有收到服务器中的任何消息。
我已经从我的电脑中完成了public class UDPClient {
private final static int TCP_PORT = 5202;
private DatagramSocket socket;
private InetAddress address;
private byte[] buf;
public UDPClient() throws SocketException, UnknownHostException {
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
}
public String sendEcho(String msg) throws IOException {
buf = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, TCP_PORT);
socket.send(packet);
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
return received;
}
public void close() {
socket.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
UDPClient udpClient = new UDPClient();
for (;;) {
TimeUnit.SECONDS.sleep(3);
System.out.println
(udpClient.sendEcho("cullons"));
}
}
}
结果:
nc -vzu 214.146.86.201 5202
但服务器在 MacBook-Pro-de-lopes:$ nc -vzu 214.146.86.201 5202
found 0 associations
found 1 connections:
1: flags=82<CONNECTED,PREFERRED>
outif (null)
src 192.166.26.140 port 56827
dst 214.146.86.201 port 5202
rank info not available
Connection to 214.146.86.201 port 5202 [udp/*] succeeded!
和LOG.info("socket InetAddres: " + socket.getInetAddress());
上打印 null
我也尝试在服务器LOG.info("socket RemoteSocketAddress: " + socket.getRemoteSocketAddress());
中使用相同的结果
答案 0 :(得分:1)
最可能的问题可能是服务器上的5202端口无法从客户端访问。端口及其可访问性可能与TCP不同,但无论如何总是有可能中间有人丢弃您的数据包。
最简单的解决方法是尝试在服务器上运行客户端和服务器代码(214.146.86.201)。如果它可以连接意味着肯定存在通信问题(似乎)你可以使用Netcat检查here所述。我自己没试过。