- 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[] data = line.getBytes();
- DatagramPacket dp = new DatagramPacket(data,data.length,InetAddress.getByName("192.168.1.101"),10002);
- ds.send(dp);
- }
- }
- catch (Exception e)
- {
- throw new RuntimeException("发送端失败!");
- }
- }
- }
- 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 = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());
- System.out.println("ip:"+ip+"data:"+data);
- }
- }
- catch (Exception e)
- {
- throw new RuntimeException("接受端失败!");
- }
- }
- }
- class ChatDemo
- {
- public static void main(String[] args) throws Exception
- {
- Send s = new Send(new DatagramSocket());
- Rece r = new Rece(new DatagramSocket(10002));
- new Thread(s).start();
- new Thread(r).start();
- }
- }
复制代码
以上是测试的代码,问题是,以上代码使用的是一个java虚拟机,请问,怎么样进行测试呢?
通过测试,以上的代码确实是运行了发送端和接收端的测试方法的。只是不知道怎么才能进行聊天,特此请教。 |