在udp编程时 是否是数据传输的特别慢 为什么我写个程序 半天接收不到 是代码有问题吗
发送端:ackage netTest;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UdpSendTest1
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
String txt = "Hello World!!!";
byte[] by = txt.getBytes();
DatagramPacket dp = new DatagramPacket(by,by.length,InetAddress.getByName("localhost"),10000);
ds.send(dp);
ds.close();
}
}
接收端:
package netTest;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpAcceptTest1
{
public static void main(String[] args) throws IOException
{
DatagramSocket ds = new DatagramSocket(10000);
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by,by.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String txt = new String(dp.getData(),0,dp.getData().length);
System.out.println(ip);
System.out.println(port);
System.out.println(txt);
ds.close();
}
}
|
|