只能发送,却收不到
import java.io.*;
import java.net.*;
class sent implements Runnable
{
private DatagramSocket ds;
public sent(DatagramSocket ds)
{
this.ds=ds;
}
public void run()//throws Exception//被覆盖的方法未抛出Exception
{
try
{
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
String line =null;
while ((line=buff.readLine())!=null)
{
if (line.equals("over"))
{
break;
}
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10002);
ds.send(dp);
}
buff.close();
}
catch (Exception e)
{
throw new RuntimeException("发送失败");
}
}
}
class rec implements Runnable
{
private DatagramSocket ds;
public rec(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());
int port = dp.getPort();
System.out.println(data+"::"+ip+"::"+port);
}
}
catch (Exception e)
{
throw new RuntimeException("接受失败");
}
}
}
class day2310
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
DatagramSocket ds1 = new DatagramSocket(10002);
sent s = new sent(ds);
rec r = new rec(ds1);
Thread t1 = new Thread(s);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
} |