黑马程序员技术交流社区

标题: UDP聊天 版 求解释 [打印本页]

作者: 刘茂林    时间: 2013-5-31 16:55
标题: UDP聊天 版 求解释
本帖最后由 刘茂林 于 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)


作者: 娄田田    时间: 2013-5-31 17:26
运行没有错啊,你再试试吧
作者: Super_Class    时间: 2013-5-31 18:23
你的没有包名啊。

你的classpath被更改了。类加载器加载不了
作者: 花开花落总相似    时间: 2013-5-31 21:15
Exception in thread "main" java.lang.NoClassDefFoundError: UDPTest (wrong name:
Socket2/UDPTest)
  这个的意思是加载不了 主函数 你看看你的那个jar包搞进去没  
  也就是你的classpath必须要配置到你的那个 tool的jar包中  
不过我很奇怪 你怎么这个错了
作者: 刘茂林    时间: 2013-6-1 10:01
算了。。就这样吧阿





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2