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 bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while ((line=bufr.readLine())!=null)
{
if ("888".equals(line))
{
break;
}
byte[] buf=line.getBytes();
DatagramPacket da=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.101"),30002);
ds.send(da);
}
ds.close();
}
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 data=new String(dp.getData(),0,dp.getLength());
String ip=dp.getAddress().getHostAddress();
System.out.println("ip="+ip+"-----"+"data="+data);
}
}
catch (Exception e)
{
throw new RuntimeException("接收端异常!请注意!");
}
}
}
public class UdpDemo3
{
public static void main(String[] args) throws Exception
{
DatagramSocket sendsocket=new DatagramSocket();
DatagramSocket recisocket=new DatagramSocket(30001);
new Thread(new Send(sendsocket)).start();
new Thread(new Rece(recisocket)).start();
}
}
在Dos窗口中执行完一次再次执行时为什么总是提示地址在使用中?
|