//UDP-键盘录入方式数据
import java.net.*;
import java.io.*;
class UdpSend2
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();//创建UDP服务ds
//键盘输入 ,InputStreamReader单字节()外面套BufferedReader()流字符
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line=bufr.readLine())!=null)//判断没有到结尾,read阻塞式方法
{
if ("886".equals(line))//判断如果输入886
break;
byte[] buf = line.getBytes();//String line 通过方法getBytes() 变成数组byte[] buf,因为封包要使用数组做对象参数
DatagramPacket dp = //数据封包,参数(数组,数组长度,主机地址InetAddress.getByName(),端口)
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.254"),10000);//封包DatagramPacket,这里的主机地址是接收人的地址
ds.send(dp);//udp服务ds 发送封包dp
}
ds.close();
}
}
class UdpRece2
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(10001);//创建UDP服务ds,监听端口10001
while (true)//循环接收
{
byte[] buf = new byte[1024];//数组作为缓冲区
DatagramPacket dp = new Datagrampacket(buf,buf.length);数据封包,参数(数组,数组长度
ds.receive(dp);//接收数据
String ip = dp.getAddress().getHostAddress();//使用数据包dp的获取地址方法。
//先getAddress()返回InetAddress对象,再用InetAddress的方法getHostAddress()返回IP地址。
String data = new String(dp.getData(),0,dp.getLength());//从数据包dp变的数组里面获取数据变成字符串String data
//返回byte[] 字节数组 , getData() //返回数据缓冲区
//new String()的构造方法(byte[],offset,length),把byte[] 字节数组 变成String
//返回int , getLength() //返回将要发送或接收到的数据的长度。
System.out.println(ip+":"+data);
}
//接收端,不用写关闭方法,为了接收数据
}
}
UDP-键盘录入方式数据
最新推荐文章于 2021-11-23 17:13:41 发布