黑马程序员技术交流社区

标题: UDP多线程收发信息 [打印本页]

作者: 草上飞    时间: 2012-11-8 19:12
标题: UDP多线程收发信息
import java.io.*;
import java.net.*;
class Send implements Runnable
{
private DatagramSocket ds;
public Send(DatagramSocket ds)
{
  this.ds=ds;
}
public void run()
{
  try
  {
   BufferedReader br=
   new BufferedReader(new InputStreamReader(System.in));
   String line=null;
   while ((line=br.readLine())!=null)
   {
    if("886".equals(line))
     break;
    byte[] by=(line).getBytes();
    DatagramPacket dp=
     new DatagramPacket(by,by.length,InetAddress.getByName("192.168.2.255"),2000);//255是表示赋给192.168.2.这个局域内的 所有主机
    ds.send(dp);
   }
  }
  catch (Exception e)
  {
   throw new RuntimeException("发送失败!");
  }

}

}
class Receive implements Runnable
{
private DatagramSocket ds;
public Receive(DatagramSocket ds)
{
  this.ds=ds;
}
public void run()
{
  try
  {
   while (true)
   {byte[] by=new byte[1024];
   DatagramPacket dp=new DatagramPacket(by,by.length);//创建一个接收by.length的数据包
   ds.receive(dp);//将ds接收到的 数据存入dp包中
   String data=new String(dp.getData(),0,dp.getLength());//获取接收到的数据
   String ip=dp.getAddress().getHostAddress();//获取ip
   System.out.println(ip+"::  "+data);  
   }
   
  }
  catch (Exception e)
  {
   throw new RuntimeException("接收失败!");
  }
}
}
class Udpthread
{
public static void main(String[] args) throws Exception
{
  DatagramSocket send=new DatagramSocket();
  DatagramSocket receive=new DatagramSocket(2000);
  new Thread(new Send(send)).start();//创建发信息线程
  new Thread(new Receive(receive)).start();//创建收信息线程
}
}






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