当前位置: 代码迷 >> J2SE >> 一端UDP程序,该如何解决
  详细解决方案

一端UDP程序,该如何解决

热度:79   发布时间:2016-04-24 01:20:38.0
一端UDP程序
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();
执行完后这个send socket关闭连接,但是数据是发送出去了呀,然后执行
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
  相关解决方案