[Java] 纯文本查看 复制代码
package datagramsocket;
public class TalkDemo {
public static void main(String[] args) {
//创建实现了Runnable接口的子类对象发送端
SendThreadDemo std = new SendThreadDemo();
//创建实现了Runnable接口的子类对象接收端
ReceiveThreadDemo rtd = new ReceiveThreadDemo();
//创建线程对象
Thread t1 = new Thread(std);
Thread t2 = new Thread(rtd);
//开启线程
t1.start();
t2.start();
}
}
[Java] 纯文本查看 复制代码
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class SendThreadDemo implements Runnable {
@Override
public void run() {
try{
while(true){
//创建发送端DatagramSocket 对象
DatagramSocket ds = new DatagramSocket();
//创建数据并打包
/*
* DatagramPacket:此类表示数据报包
* 数据byte[]
* 设备的地址 ip
* 进程的地址 端口号
* DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
*/
//写一个键盘录入,用来接收输入的消息
Scanner sc = new Scanner(System.in);
System.out.println(InetAddress.getLocalHost().getHostName()+"-->请输");
String s =sc.nextLine();
//创建一个字节数组接收输入的消息
byte[] bys = s.getBytes();
int len = bys.length;
int port = 9997;//设置端口号,这个端口号是接收端暴露出的那个端口号
InetAddress address = InetAddress.getByName("192.168.11.60");//设置接收端的IP地址
DatagramPacket dp = new DatagramPacket(bys,len,address,port);//包装数据
//发送数据
ds.send(dp);
//释放资源
ds.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
[Java] 纯文本查看 复制代码
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ReceiveThreadDemo implements Runnable {
@Override
public void run() {
try{
while(true){
//创建接收端的DatagramSocket 对象
DatagramSocket ds = new DatagramSocket(9998);
//接收数据
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
ds.receive(dp);//阻塞方法,只有接到数据才会往下执行
//解析数据
//InetAddress getAddress()
InetAddress address = dp.getAddress();
byte[] data = dp.getData();//这里也可以使用接收数据的bys数组
int length = dp.getLength();
//输出数据
System.out.println("sender-->" + address.getHostAddress());//获取主机名称并打印显示
System.out.println(new String(data,0,length));
//释放资源
ds.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}