1.UDP和TCP的区别
1.是否是一种可靠连接
UDP协议:是一种不可靠连接
TCP协议:是一种可靠连接
2.是否需要建立连接通道
UDP协议:不需要建立连接通道
TCP协议:需要建立连接通道
3.是否发送的数据大小有限制
UDP协议:有限制,因为UDP发送--->
以一种 "数据报包-->DatagramPacket"的方式
TCP协议:没有限制,连接通道里面-->使用字节流的方式来进行通信(数据写,读)
客户端--->获取通道的字节输出流--->写数据
服务端--->获取通道的字节输入流--->读数据
2.java.net.InetAddress
1.成员方法:
public static InetAddress getByName(String host)throws UnknownHostException:通过主机名称(计算机的全名)或者ip地址的文本(字符串形式),返回值代表的互联网IP地址
public String getHostAddress():通过ip地址对象获取ip地址的字符串形式
public String getHostName():通过ip地址对象获取主机名称
2.代码实现:
public class InetAddressDemo {
public static void main(String[] args) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName("10.12.156.50");
String ip = inetAddress.getHostAddress();
System.out.println(ip);
String hostName = inetAddress.getHostName();
System.out.println(hostName);
}
}
3.UDP的发送与接收代码
1.发送端步骤
(1)创建发送端Socket对象
DatagramSocket :此类表示用于发送和接收数据报数据包的套接字。
构造方法:public DatagramSocket() throws SocketException
(2)创建一个数据报包对象
创建一个"数据报包"对象DatagramPacket
构造方法:
public DatagramPacket(byte[] buf, 发送端数据
int length, 发送的长度
InetAddress address, ip地址对象
int port) 端口号
(3)使用UDP发送端的Socket对象发送数据报包
public void send(DatagramPacket p) throws IOException
(4)释放资源
public class UDPSend{
public static void main(String[] args){
DatagramSocket ds = new DatagramSocket() ;
byte[] bytes = "hello,UDP,我来了".getBytes() ;
int length = bytes.length ;
InetAddress inetAddress = InetAddress.getByName("10.12.156.50");
int port = 10086 ;
DatagramPacket dp = new DatagramPacket(bytes,length,inetAddress,port) ;
ds.send(dp) ;
ds.close() ;
}
}
2.接收端步骤
(1)创建Socket对象
public DatagramSocket(int port)throws SocketException
(2)创建一个接受容器,将发送端的数据存储进来
public DatagramPacket(byte[] buf,int length)
(3)接收
public void receive(DatagramPacket p)throws IOException
(4)通过接收端的接受容器:DatagramPacket解析真实数据
public byte[] getData():获取数据报包的缓冲真实数据
public byte[] getData():获取数据报包的缓冲区的真实长度
(5)展示数据
String的构造方法
String content = new String(bytes,0,length2) ;
public InetAddress getAddress():返回该数据报发送或接收数据报的计算机的IP地址。
(6)释放资源
public class UDPReceive {
public static void main(String[] args) throws Exception {
DatagreamSocket ds = new DatagramSocket(10086);
byte[] bytes = new byte[1024];
int length = bytes.length;
DatagramPacket dp = new DatagramPacket(bytes,length) ;
ds.receive(dp);
byte[] bytes2 = dp.getData();
int length2 = dp.getLength();
String ip = dp.getAddress().getHostAddress() ;
String content = new String(bytes2,0,length2) ;
System.out.println("data from--> "+ip+",content is-->"+content);
ds.close();
}
}
4.与多线程一起使用
1.在一个窗口里面既发送,也接收
分析:
1)需要分别创建两端的Socket对象(发送端的Socket,和接收的Socket)
2)开启两个线程:
发送端不断发送消息的线程
接收端不断的展示数据的线程
D:\program\IDEAProgram\network_programming\src\com\lq\UDP_Thread