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人家的代码,按照理论应该没问题,
我尝试了很多次,控制台为什么没反映?
解决方案 »
- Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
- java连接数据库最好的方法
- 请推荐一本好的EJB教材。
- 什么认证最有荣耀感?
- 帮我看看一个简单的 Java图形程序设计 编码!
- 请问如何以编程的方式实现JARSIGNER,就是用编程的方式对一个JAR进行签名进者有分
- 求助!怎样用JAVA编写ping程序?
- 如何填充JCheckBox的颜色,用setBackground()也不行!
- library path
- 请问JAVA中怎样去掉字符串后面的空格,谢谢!!!
- 关于复试 诸位高手 给点建议
- 请问这个界面如何实现?
发送端: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", 为什么还是没反映?