![在这里插入图片描述](https://img-blog.csdnimg.cn/20190903100042946.png)
Class InetSocketAdress:
网络编程中需要 :
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190903102154174.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190903102212161.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzk1NjQxNA==,size_16,color_FFFFFF,t_70)
构造方法:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190903102236141.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzk1NjQxNA==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190903102257911.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzk1NjQxNA==,size_16,color_FFFFFF,t_70)
静态方法:createUnresolved:
一个简单的UDP协议网络连接:
先将软件连接在自己 ip 地址 和 对应的端口上,在执行代码
用一个编号的网络连接测试工具:
实现接受和发送端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;
public class UdpSend {
public static final String IP = “192.168.43.170”;
public static final int S_PORT = 8888 ;
public static final int R_PORT = 9999 ;
public static void main(String[] args) {
DatagramSocket dgs = null;
try {
// 获取UDP协议的Socket对象
dgs = new DatagramSocket(S_PORT);
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("输入发送的语句:");
String str = sc.next().trim();
// 转换为字节
//byte[] buf = str.getBytes("utf-8");
byte[] buf = str.getBytes();
InetSocketAddress ins = new InetSocketAddress(IP , R_PORT);
// 获取UDP报文对象
DatagramPacket dgp = new DatagramPacket(buf , 0 ,buf.length ,ins );
// 发送数据
dgs.send(dgp);
System.out.println("发送成功");
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(dgs != null) {
dgs.close();
}
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class Udpreceives {
public static final String IP = "192.168.0.100";
public static final int R_PORT = 8888 ;
public static final int S_PORT = 9999 ;
public static void main(String[] args) {
DatagramSocket dgs = null;
try {
// 获取UDP协议的Socket对象
dgs = new DatagramSocket(S_PORT);
System.out.println("服务以及启动");
while(true) {
// 创建一个字节数组,用来保存发送过来的数据
byte[] buf = new byte[1024];
// 报文头对象
DatagramPacket dgp = new DatagramPacket(buf ,0 ,buf.length );
// 接受信息
dgs.receive(dgp);
String str = new String(buf , 0 ,buf.length);
System.out.println("接受到消息为---》"+str);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(dgs != null) {
dgs.close();
}
}
}
}