本帖最后由 刘茂林 于 2013-6-1 10:01 编辑
import java.net.*;
import java.io.*;
class UDPTest
{
public static void main(String[] args) throws Exception
{
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receSocket = new DatagramSocket(10001);
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}
}
// 这是发送端 使用线程 继承了runnable接口 实现 run方法
class Send implements Runnable
{
private DatagramSocket ds;
public Send(DatagramSocket ds)
{
this.ds = ds;
}
public void run()
{
try
{
// 下面就是通过键盘读数据然后封装到包中传送出去
BufferedReader bufr = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
while ((line = bufr.readLine()) != null)
{
if ("886".equals(line))
{
break;
}
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("127.0.0.1"), 10001);
ds.send(dp);
}
} catch (Exception e)
{
throw new RuntimeException("发送数据出现错误");
}
ds.close();
}
}
// 这是接收端 一样用线程 实现接口 重写run方法
class Rece implements Runnable
{
private DatagramSocket ds;
public Rece(DatagramSocket ds)
{
this.ds = ds;
}
public void run()
{
try
{
while (true)
{
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip = new String(dp.getAddress().getHostAddress());
String data = new String(dp.getData(),0,dp.getLength());
System.out.println("ip:"+ip +"说::"+data);
}
} catch (Exception ex)
{
throw new RuntimeException("接收数据时错误");
}
}
}
这个程序运行错误 求解释。
Exception in thread "main" java.lang.NoClassDefFoundError: UDPTest (wrong name:
Socket2/UDPTest)
|