网络编程
1. TCP/IP的参考模型:
Java的网络编程方面比其他的WINDOWS桌面程序要强大太多了,很多复杂的协议接口,都已经封装得很完美,功能代码只需要很少就完美实现。
OSI七层网络模型 TCP/IP四层概念模型 对应网络协议
应用层 Application 应用层 HTTP,TFTP, FTP,NFS,WAIS,SMTP
表示层 Presentation Telnet, Rlogin, SNMP, Gopher
会话层 Session SMTP, DNS
传输层 Transport 传输层 TCP, UDP
网络层 Network 网络层 IP,ICMP,ARP, RARP, AKP, UUCP
数据链路层:DataLink 数据链路层 FDDI, Ethernet, Arpanet, PDN,SLIP,PPP
物理层 Physical IEEE 802.1A, IEEE802.2到IEEE.802.11
小结:
- 如何准确的定位到网络上的一台或多台主机。
- 找到主机后如何通信。
- 确定IP和端口号。 IP 类
- 网络通信协议。 TCP和UDP类
- 万物皆对象。 InetAddress 类
IP: 用来唯一定位一台网络上的计算机。
127.0.0.1 : 本机地址localhost,相当于this.
IP地址分类: ipv4/ ipv6. 4字节组成IP和6字节组成IP。 42亿4类地址,30亿在北美,4亿在亚洲。
6类地址,是未来的地址。 ifconfig可以用来查看地址。128位,无符号整数。
A类地址:00000001, 00000000, 00000000, 00000001
:
01111110, 11111111,11111111,11111110
1.0.0.1\~ 126.255.255.254
B类地址: 10000000, 00000001, 00000000, 00000001
:
10111111, 11111110, 11111111,11111110
128.1.0.1\~ 191.254.255.254
- C类地址:11000000, 00000000, 00000001, 00000001
~11011111, - 11111111, 11111110, 11111110
192.0.1.1~223.255.254.254 - D类地址:224.0.0.1~239.255.255.254
- E类地址: 240.0.0.0~255.255.255.254
//参数也可以用localhost或者127.0.0.1
InetAddress inetAddress = InetAddress.getByName("www.Apple.com");
使用方法:inetAddress.getHostAddress(); inetAddress.getHostName(); 得到对应IP和域名
2. TCP的java实现:
- 客户端:
- 连接服务器Socket(serverIP, port); //port可以是约定,
serverIP 用InetAddress.getByName("127.0.0.1"); 获得。 - 发送消息. 用os=socket.getOutputStream();得到一个发送流对象。
然后再调用对象os的write("这是一个消息哦",getbytes());方法。
- 连接服务器Socket(serverIP, port); //port可以是约定,
- 服务器端:
- 建立服务器端口 ServerSocket ss= new ServerSock(port);
再建立一个通信端口变量socket,这里不用实例化。 - 用通信端口指向服务器端口的accept: socket=ss.accept();
等待用户的连接 accept - 接收用户的消息 定义一个输入流对象 InputStream is=socket.getInputStream();
用socket的对应方法得到输入流。 - 繁琐的流处理
用ByteArrayOutputStream()获得流信息并输出。
- 建立服务器端口 ServerSocket ss= new ServerSock(port);
3. UDP的java实现:
- 发送端:
用DatagramSocket建立套接字; 用DatagramPacket 建立UDP数据包。
java
DatagramPacket pkt = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,
inetAddress, port);
sck.send(pkt); //send方法发送出去就可以了,不用管连接没连接。
sck.close();
- 接收端:
同样用DatagramSocket建立套接字; 用DatagramPacket 建立UDP数据包。
java
sct = new DatagramSocket(port);
//繁琐的缓冲数据处理
byte[] buff=new byte[1024];
DatagramPacket pckt = new DatagramPacket(buff, 0, buff.length);
sct.receive(pckt); //对应send 方法,用receive 形成一个阻塞接收。
//以下是需要的信息: pckt.getAddress().getHostName()或getHostAddress();
new String(pckt.getData(), 0, pckt.getLength()); //这个可以得到数据内容。
sct.close();
UDP的特点就是没有谁做服务器的概念,只要定义好相同的端口,谁都可以发送,谁都可以接收。
4. URL的类使用:
统一资源定位符: 可以定位网上的的某一个资源。
协议://ip地址: 端口号/项目名/资源位置。
new URL(地址String);
getProtocol()得到协议名。getHost();得到主机。getPort()得到端口。getPath()得到地址。
getFile()得到文件。getQuery()得到查询名。
利用URL下载文件:
java
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection(); //返回URL的连接
InputStream strm =urlCon.getInputStream(); //从连接里得到流资源
FileOutputStream fos =new FileOutputStream(str文件流的文件名);
//繁琐的读缓冲区
byte[] buff =new byte[1024];
int len
while((len=inputStream.read(buff))!=1){
fos.write(buffer, 0, len); //往信件的文件流中写入连接流。
}
fos.close();
strm.close();
urlCon.disconnect();
几行代码就可以搞定网络资源的文件了。
Apache Tomcat的启动:
cd /Users/用户名/tomcat/bin,进入到tomcat的bin目录下
输入:./startup.sh + 回车,
如出现错误:"Permission denied"(操作失败,缺少权限)
输入命令,赋予超级管理员权限sudo chmod 755 *.sh + 回车
再次执行命令:./startup.sh + 回车
打开浏览器,输入网址 http://localhost:8080/ ,如果出现一只三角猫,表示tomcat安装成功
关闭的话:./shutdown.sh + 回车
核心配置文件:./conf/server.xml
5. 示例
实现一个标准的TCP/IP通信
下面是服务端,需要先启动,形成一个通信阻塞。核心方法: ServerSocket; Socket; ByteArrayOutputStream; InputStream; buffer的应用以及各种异常处理。
java
package UseInternet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo01 {
public static void main(String[] args) {
ByteArrayOutputStream baos = null;
ServerSocket serverSocket =null;
Socket socket =null;
InputStream is =null;
try {
serverSocket = new ServerSocket(9999);
socket = serverSocket.accept(); //这里形成一个阻塞,等待接收客户端信息.
is = socket.getInputStream();
baos= new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2 = 0;
while ((len2=is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
System.out.println("Got msg");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos!=null){
try {
baos.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (is!=null){
try{
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
};
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
下面是客户端代码。
java
package UseInternet;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDemo1 {
public static void main(String[] args) {
Socket socket =null;
OutputStream os =null;
try {
//获得服务器的IP和端口号
InetAddress serverIP= InetAddress.getByName("127.0.0.1");
int port = 9999;
//创建一个socket连接
socket = new Socket(serverIP, port);
os = socket.getOutputStream();
os.write("你好,这是一个网络外发的消息OS".getBytes());
// 关键修复:1.刷新输出流,确保数据全部发送 2.关闭输出流,发送流结束标记
os.flush();
socket.shutdownOutput();
} catch (UnknownHostException e) {
e.printStackTrace();
//throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace(); // 建议不要直接throw RuntimeException,方便排查问题
}finally {
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
解析各种网址的IP信息
了解InetAddress.getByName; InetAddress.getLocalHost; getAddress; getCanonicalHostName; getHostAddress; getHostName等常用方法。
java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestInetAddress {
public static void main(String[] args) {
try{
//查询本机地址
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1);
InetAddress inetAddress2 = InetAddress.getByName("localhost");
System.out.println(inetAddress2);
InetAddress inetAddress3 = InetAddress.getLocalHost();
System.out.println(inetAddress3);
InetAddress inetAddress4= InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress4);
InetAddress inetAddress5= InetAddress.getByName("www.Apple.com");
System.out.println(inetAddress5);
System.out.println("====================================");
System.out.println(inetAddress5.getAddress()); //拿IP地址的字节数据(底层二进制,很少用)
System.out.println(inetAddress5.getCanonicalHostName()); //拿规范主机名,强制反向DNS解析
System.out.println(inetAddress5.getHostAddress()); //只拿IP地址字符串(最常用)
System.out.println(inetAddress5.getHostName()); //拿主机名(优先用已知的,不强制反向解析
}catch (UnknownHostException e){
System.out.println(e);
e.printStackTrace();
}
}
}
UDP发送与接收
服务端:需要了解类和方法:DatagramSocket; DatagramPacket; datagramSocket.receive; datagramSocket.send.
java
package UseInternet;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class TestUDPserver {
public static void main(String[] args) throws Exception {
DatagramSocket sct;
sct = new DatagramSocket(8888);
byte[] buff=new byte[1024];
DatagramPacket dgp= new DatagramPacket(buff,0,buff.length);
sct.receive(dgp); //阻塞接收
System.out.println(dgp.getAddress().getHostName()+"|||"+dgp.getAddress().getHostAddress());
System.out.println(new String(dgp.getData(),0,dgp.getLength()));
sct.close();
}
}
客户端:严格说,没有服务端和客户端的区别,都是使用同样的DatagramSocket类。都可以发送和接收。
java
package UseInternet;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class TestUDP {
public static void main(String[] args) throws Exception {
DatagramSocket skt = new DatagramSocket();
String msg="这是一个UDP的发送测试";
InetAddress idr =InetAddress.getByName("localhost");
int port =8888;
DatagramPacket dgp = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,idr,port);
skt.send(dgp); //这里不需要建立连接
skt.close();
}
}
网络资源下载
核心类:HttpURLConnection; FileOutputStream;
java
package UseInternet;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UseURLDownLoad {
public static void main(String[] args) throws IOException {
URL url = new URL("https://himg.bdimg.com/sys/portrait/item/pp.1.f0337f07.qLRrh6j5cr5u6SFhRwgS1A?_t=1764409787836");
HttpURLConnection urlCon =(HttpURLConnection) url.openConnection();
InputStream strm= urlCon.getInputStream();
FileOutputStream fos = new FileOutputStream("阳光和青草.jpg");
byte[] buff = new byte[1024];
int len;
while ((len=strm.read(buff))!=-1){
fos.write(buff,0,len);
}
fos.close();
strm.close();
urlCon.disconnect();
}
}
对,就上面这么短一点的代码,只需要把URL换成网页中的各种元素资源,就可以随意的在网页上荡取视频,音乐,图片,堪比歪瓜!