目录
网络通信的要素
- IP和端口号
- 网络通信协议
网络通信协议
- 网络通信协议,即一定的通信规则,有两套网络参考模型
网络参考模型与对应的协议
- OSI参考模型过于理想化,未能在因特网上进行广泛推广
- TCP/IP参考模型(或TCP/IP协议)是目前事实上的国际标准
不同模型层次对数据的处理
TCP/IP协议簇
TCP 和 UDP
TCP三次握手
TCP四次挥手
IP和端口号
InetAddress类
域名与DNS
InetAddress类的构造器和常用方法
try {
InetAddress inet1 = InetAddress.getByName("www.baidu.com");
System.out.println(inet1);// www.baidu.com/14.119.104.254
InetAddress inet2 = InetAddress.getByName("127.0.0.1");
System.out.println(inet2); // /127.0.0.1
System.out.println(inet2.getHostName()); // 127.0.0.1
System.out.println(inet2.getHostAddress()); // 127.0.0.1
//获取本地ip
InetAddress inet3 = InetAddress.getLocalHost();
System.out.println(inet3);// DESKTOP-JT2RL/192.168.0.26
} catch (UnknownHostException e) {
e.printStackTrace();
}
Socket 套接字
- IP + 端口号 组成套接字
Socket 构造器与常用方法
基于Socket的TCP编程
- 客户端
- 服务端
阻塞与总结
-
socket.getInputStream().read()
会发生阻塞的根本原因时对方的输出流没有末尾标记,导致不能读到"-1",产生阻塞,以下情况会导致阻塞发生- 对方通过
socket.getOutputStream().write(...)
传输的内容为空时(非null) - 对方没有执行
socket.shutdownOutput()
socket.shutdownOutput()
会在输出流中添加末尾标记 - 对方通过
-
对方 socket 连接断开后,本方使用输出流不报错,使用输入流报错
-
服务器端要比客户端先启动,否则当客户端创建Socket对象时会报错
UDP编程
DatagramSocket 类
DatagramPacket 类
发送端和接收端
//发送端
// 1. 创建 DatagramSocket 对象
DatagramSocket socket = new DatagramSocket();
String str = "我是UDP方式发送的导弹";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
// 2. 创建 DatagramPacket 对象
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
// 3. 使用 DatagramSocket 对象 发送
socket.send(packet);
// 4. 关闭 DatagramSocket 对象
socket.close();
//接收端
// 1. 创建 DatagramSocket 对象
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[100];
// 2. 创建 DatagramPacket 对象
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
// 3. 使用 DatagramSocket 对象 发送
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
// 4. 关闭 DatagramSocket 对象
socket.close();
URL编程
URL类
URL类构造器
URL类常用方法
URLConnection类
通过URL与URLConnection实现URL编程
HttpURLConnection urlConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
// 1. 创建 URL 对象
URL url = new URL("http://localhost:8080/examples/beauty.jpg");
// 2. 创建 HttpURLConnection 对象
urlConnection = (HttpURLConnection) url.openConnection();
// 3. 建立连接
urlConnection.connect();
// 4. 创建 输入输出流
is = urlConnection.getInputStream();
fos = new FileOutputStream("day10\\beauty3.jpg");
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
System.out.println("下载完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(urlConnection != null){
// 关闭连接
urlConnection.disconnect();
}
}