原理
两个线程,一个线程接收消息,一个线程发送消息。
发送线程
步骤
1、实现Runna接口,并写构造函数
2、提供数据,数据从键盘中获取,并将数据封装到数据包中
3、通过socket服务的发送功能,将数据包发出去。
4、发送886,结束发送。
代码示例
class Send implements Runnable{
private DatagramSocket ds;
public Send(DatagramSocket ds){
this.ds = ds;
}
public void run(){
try{
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
while(line!=null){
if(line.equals("886"))
break;
byte[] buff = line.getBytes();
DatagramPacket dp = new DatagramPacket(buff,buff.length,InetAddress.getByName("局域网广播ip"),10002);
ds.send(dp);
line = sc.nextLine();
}
}
catch(Exception e){
throw new RuntimeException("发送端失败");
}
}
}
接收线程
步骤
1、同发送线程。
2、定义一个数据包,存储接收到的数据
3、receive方法,将接收到的数据存到2的数据包
4、通过数据包对象的特有功能,将数据取出,打印在控制台
代码示例
class Receive implements Runnable{
private DatagramSocket ds;
public Receive(DatagramSocket ds){
this.ds = ds;
}
public void run(){
try{
while(true){
byte[] buff = new byte[1024];
DatagramPacket dp = new DatagramPacket(buff,buff.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+":"+data);
}
}
catch(Exception e){
throw new RuntimeException("接收端失败");
}
}
}
主程序
启动两个线程
class ChatDemo{
public static void main(String[] args)throws Exception{
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receiveSocket = new DatagramSocket(10002);
new Thread(new Send(sendSocket)).start();
new Thread(new Receive(receiveSocket)).start();
}
}