import java.io.*;
import java.net.*;class DGSClient
{
public static void main (String [] args)
{
String host="localhost";
if(args.length==1)
host=args[0];
DatagramSocket s=null;
try
{
s=new DatagramSocket();
byte []buffer;
buffer=new String("Send me a datagram").getBytes();
InetAddress ia=InetAddress.getByName(host);
DatagramPacket dgp =new DatagramPacket(buffer,buffer.length,ia,10000);
s.send(dgp);
byte [] buffer2 =new byte [100];
dgp = new DatagramPacket(buffer2,buffer.length,ia,10000);
s.receive (dgp);
System.out.println(new String(dgp.getData ()));
}
catch(IOException e)
{
System.out.println(e.toString());
}
finally
{
if(s!=null)
s.close();
} //end finally
} //end main
} //end classc:\workplace\java DGSClient 一半天没反应,我是copy人家的代码,按照理论应该没问题,
我尝试了很多次,控制台为什么没反映?
import java.net.*;class DGSClient
{
public static void main (String [] args)
{
String host="localhost";
if(args.length==1)
host=args[0];
DatagramSocket s=null;
try
{
s=new DatagramSocket();
byte []buffer;
buffer=new String("Send me a datagram").getBytes();
InetAddress ia=InetAddress.getByName(host);
DatagramPacket dgp =new DatagramPacket(buffer,buffer.length,ia,10000);
s.send(dgp);
byte [] buffer2 =new byte [100];
dgp = new DatagramPacket(buffer2,buffer.length,ia,10000);
s.receive (dgp);
System.out.println(new String(dgp.getData ()));
}
catch(IOException e)
{
System.out.println(e.toString());
}
finally
{
if(s!=null)
s.close();
} //end finally
} //end main
} //end classc:\workplace\java DGSClient 一半天没反应,我是copy人家的代码,按照理论应该没问题,
我尝试了很多次,控制台为什么没反映?
发送端:import java.net.*;public class UdpSend
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
String message = "Welcome to Java.";
DatagramPacket dp = new DatagramPacket(message.getBytes(),message.getBytes().length,InetAddress.getByName("127.0.0.1"),5000);
ds.send(dp);
ds.close();
}
}接收端:import java.net.*;public class UdpReceive
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(5000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String message = new String(dp.getData(),0,dp.getLength()) + " from " + dp.getAddress() + ":" + dp.getPort();
System.out.println(message);
ds.close();
}
}
UDP通信,你要先运行接收端,再运行发送端,始终监视端口到来的数据信息,这样才能显示接收到信息。
你的程序,先执行了发送,后执行接受,这样数据就丢失了~~你的明白~~
我只懂tcp,不懂udp啊,将 String host="localhost"; 改成String host="www.baidu.com", 为什么还是没反映?