UDP例子得一点问题

angelcm51 2008-12-05 12:29:35
import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive
{
public static void main(String args[])
{
try
{
if(args.length!=1)
throw new IllegalArgumentException("Wrong number of args");
int port=Integer.parseInt(args[0]);
DatagramSocket dsocket=new DatagramSocket(port);
byte[] buffer=new byte[2048];
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
for(;;)
{
dsocket.receive(packet);
String msg=new String(buffer,0,packet.getLength());
System.out.println(packet.getAddress().getHostName()+":"+msg);
packet.setLength(buffer.length);
}
}
catch(Exception e)
{
System.err.println(e);
}
}
}

import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPSend
{
public static void main(String args[])
{
try
{
if(args.length<3)
throw new IllegalArgumentException("Wrong number of args");
String host=args[0];
int port=Integer.parseInt(args[1]);
byte[] message;
String msg=args[2];
message=msg.getBytes();
InetAddress address=InetAddress.getByName(host);
DatagramPacket packet=new DatagramPacket(message,
message.length,address,port);
DatagramSocket dsocket=new DatagramSocket();
dsocket.send(packet);
dsocket.close();
}
catch(Exception e)
{
System.err.println(e);
}
}
}


javac编译都没问题
java编译运行后都是抛出异常 "Wrong number of args"

怎么回事呢?
...全文
121 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
SylvanLiu 2008-12-05
  • 打赏
  • 举报
回复
很明显:
if(args.length!=1)
throw new IllegalArgumentException("Wrong number of args");
....
if(args.length<3)
throw new IllegalArgumentException("Wrong number of args");

参数不对
goodmrning 2008-12-05
  • 打赏
  • 举报
回复
ding!
xiaolong19870717 2008-12-05
  • 打赏
  • 举报
回复
要用类 ByteArrayInputStream,和类 ByteArrayOutputStream其中的数据被写入一个 byte 数组
云上飞翔 2008-12-05
  • 打赏
  • 举报
回复
[Quote=引用楼主 angelcm51 的帖子:]
Java codeimport java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive
{
public static void main(String args[])
{
try
{
if(args.length!=1)
throw new IllegalArgumentException("Wrong number of args");
int port=Integer.parseInt(args[0]);
DatagramSocket dso…
[/Quote]
答:你运行程序的方式不对.
1)运行UDPReceive 方式是(设端口号是:9999,IP:192.168.1.177):
java UDPReceive 9999

2)运行UDPSend方式是(设发送给UDPReceive所在的机器的信息是:"你好吗?"):
java UDPSend 192.168.1.177 9999 "你好吗?"


myjava_024 2008-12-05
  • 打赏
  • 举报
回复
throw new IllegalArgumentException("Wrong number of args");
throw new IllegalArgumentException("Wrong number of args");
报的这个错误嘛

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧