本帖最后由 谢永烽 于 2015-5-9 14:29 编辑
import java.net.*;
import java.io.*;
//Udp发送线程
class UdpSend implements Runnable
{
//1,定义Socket服务引用
private DatagramSocket ds;
public UdpSend(DatagramSocket ds)
{
this.ds = ds;
}
public void run()
{
try
{
//2,确定数据,从键盘录入,并把键盘录入的数据封装成数据包
DatagramPacket dp = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line=br.readLine())!=null)
{
byte[] buf = line.getBytes();
dp =new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.2"),10002);
//3,通过Socket服务将已有的数据包发送出去
ds.send(dp);
if("886".equals(line));
{
break;
}
}
//4,关闭资源
//ds.close();
}
catch (Exception e)
{
throw new RuntimeException("发送数据失败啦");
}
}
}
//Udp接收线程
class UdpRece implements Runnable
{
//1,定义Socket服务引用
private DatagramSocket ds;
public UdpRece(DatagramSocket ds)
{
this.ds = ds;
}
public void run()
{
try
{
//一直处于接收状态
while (true)
{
//2,定义数据包,用于存数数据
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
//3,通过Socket服务,将数据接收并存储到数据包中
ds.receive(dp);
//4,通过数据包的方法获取其中的数据
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println("ip:"+ip+" 信息:"+data);
}
//5关闭资源
//ds.close();
}
catch (Exception e)
{
throw new RuntimeException("接收端接收数据失败啦");
}
}
}
class UdpChatDemo
{
public static void main(String[] args) throws Exception
{
new Thread(new UdpSend(new DatagramSocket())).start();
new Thread(new UdpRece(new DatagramSocket(10002))).start();
}
}
|