A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 新航向 于 2014-9-8 08:47 编辑

以下代码比本上和视频里的一样,在本人机子上为什么会出错?(即输入内容后就卡住,也不打印地址和内容)请大神们帮忙看看,谢谢!
  1. import java.io.*;
  2. import java.net.*;
  3. class Send implements Runnable
  4. {
  5.     private DatagramSocket ds;
  6.     Send(DatagramSocket ds)
  7.     {
  8.         this.ds = ds;
  9.     }
  10.     public void run()
  11.     {
  12.         try
  13.         {
  14.             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  15.             String line = null;
  16.             while ((line=br.readLine())!=null)
  17.             {
  18.                 if(!line.equals("886"))
  19.                     break;
  20.                 byte[] buff = line.getBytes();
  21.                 DatagramPacket dp = new DatagramPacket(buff,buff.length,InetAddress.getLocalHost(),54321);
  22.                 ds.send(dp);
  23.              }
  24.             ds.close();
  25.          }
  26.          catch (Exception e)
  27.          {
  28.                 throw new RuntimeException("传输失败");
  29.           }
  30.      }
  31. }
  32. class Receive implements Runnable
  33. {
  34.     private DatagramSocket ds;
  35.     Receive(DatagramSocket ds)
  36.     {
  37.         this.ds = ds;
  38.     }
  39.     public void run()
  40.     {        
  41.         try
  42.         {
  43.             while (true)
  44.             {
  45.                   byte[] buff = new byte[1024];
  46.                   DatagramPacket dp = new DatagramPacket(buff,buff.length);
  47.                   ds.receive(dp);
  48.                   String ip = dp.getAddress().getHostAddress();
  49.                   String data = new String(dp.getData(),0,dp.getLength());
  50.                   System.out.println(ip+"::"+data);
  51.               }        
  52.            }
  53.            catch (Exception e)
  54.            {
  55.                  throw new RuntimeException();
  56.            }
  57.     }
  58. }
  59. class ChatDemo
  60. {
  61.     public static void main(String[] args) throws Exception
  62.     {
  63.         DatagramSocket sendSocket = new DatagramSocket();
  64.         DatagramSocket receiveSocket = new DatagramSocket(54321);
  65.         new Thread(new Send(sendSocket)).start();
  66.         new Thread(new Receive(receiveSocket)).start();
  67.     }
  68. }
复制代码



1.png (30.41 KB, 下载次数: 24)

1.png

3 个回复

倒序浏览
明天帮你看看,,现在的机子没环境
回复 使用道具 举报
不服™け你咬我 发表于 2014-9-7 23:36
明天帮你看看,,现在的机子没环境

问题已经找到,if判断语句反了
还是多谢你了!
回复 使用道具 举报
好厉害啊,学习一下
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马