- Java code
import java.net.*;public class MainClass4{ public static void main(String[] args) { PacketSender ps=new PacketSender(); PacketReceiver pc=new PacketReceiver(); }}class PacketReceiver { public static void main(String[] args) throws Exception { byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); DatagramSocket socket = new DatagramSocket(5002); socket.receive(packet); System.out.println(packet.getSocketAddress()); System.out.println(new String(packet.getData(),0,packet.getLength())); socket.close(); }}class PacketSender { public static void main(String[] args) throws Exception { byte[] buffer = "data".getBytes(); InetAddress addr=InetAddress.getByName("localhost"); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, addr, 5002); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); }}
不知道我对UDP的理解哪里错了,上面这段程序编译没问题,运行什么都不输出就结束了,UDP不是面对连接的通信,也就是说
- Java code
PacketSender ps=new PacketSender();
- Java code
PacketReceiver pc=new PacketReceiver();
------解决方案--------------------
先打开server,在打开client端,服务端要先开着吧
比如
PacketReceiver pc=new PacketReceiver();
Thread.sleep(2000);//try catch,等待服务端完全开启
PacketSender ps=new PacketSender();
试一试
------解决方案--------------------
应该是服务器代码中new String()这里写错了,你在试试看。
//System.out.println(packet.getAddress().getHostAddress());
System.out.println(packet.getAddress().getHostAddress()+":"+new String(buffer,0,packet.getLength()));//输出:127.0.0.1:data