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();//创建收信息线程
}
}
|