import java.net.*;
import java.io.*;
class Sender implements Runnable
{
public void run()
{
try
{
DatagramSocket ds=new DatagramSocket(1234);//通过DategramSocket的对象建立UDP服务器既是用户数据协议:user datagram protocol
byte[] b;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while((b=br.readLine().getBytes())!=null)
{
DatagramPacket dp=new DatagramPacket(b,0,b.length,InetAddress.getByName("192.168.43.204"),2345);//确定数据并且将数据封包
ds.send(dp);//通过UDP服务器发送数据
}
}
catch (Exception e)
{
throw new RuntimeException();
}
}
}
class Recer implements Runnable
{
public void run()
{
try
{
DatagramSocket ds=new DatagramSocket(2345);//通过DategramSocket的对象建立UDP服务器既是用户数据协议:user datagram protocol
byte[] b=new byte[1024];
while (true)
{
DatagramPacket dp=new DatagramPacket(b,b.length);//确定数据并且将数据封包
ds.receive(dp);//通过UDP服务器接受数据b
System.out.println(dp.getAddress().getHostAddress()+":"+dp.getPort()+new String(dp.getData(),0,dp.getLength()));
}
}
catch (Exception e)
{
throw new RuntimeException();
}
}
}
class Liaotian
{
public static void main(String[] args) throws Exception
{
new Thread(new Sender()).start();
new Thread(new Recer()).start();
}
}
困惑有下:
1,多线程在这儿为什么不加锁
2,这个小程序上面的在对数据进行封包的时候为何不能搞个广播地址,192.168.1.255;一弄成这样就接收不到 |