1. 网络编程概述
Java是Internet上的语言,它从语言级上提供了对网络应用程序的支持,程序员能够很容易开发常见的网络应用程序
Java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在 Java 的本机安装系统里,由JVM进行控制
并且Java实现了一个跨平台的网络库,程序员面对的是一个统一的网络编程环境
网络编程的目的在于:直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯
网络编程中的两个主要问题:
- 如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
- 找到主机后如何可靠高效地进行数据传输
2. 网络通信要素
2.1 通信要素概述
网络通信中的两个要素:
- IP和端口号:解决确认主机和定位主机上的特定应用问题
- 网络通信协议:解决可靠高效数据传输问题
2.2 通信要素1:IP和端口号
IP地址
- 每个主机都有自己的IP地址和域名,两个都可以确定一个主机,只是表现方式不同
- 本机的IP地址可以用"127.0.0.1"表示
- Java中用InetAddress类表示IP类,其构造器被私有化,只能用静态方法实例化:getByName()、getLocalHost()
- 有两个常用方法:getHostName()、getHostAddress()
//导入的包有:import java.net.InetAddress;import java.net.UnknownHostException;
public class InteAdressTest {
public static void main(String[] args) {
try {
//实例化可以填入IP地址
InetAddress inet1 = InetAddress.getByName("192.168.10.14");
System.out.println(inet1);
//实例化可以填入域名
InetAddress inet2 = InetAddress.getByName("www.atguigu.com");
System.out.println(inet2);
//实例化可以填入本机地址
InetAddress inet3 = InetAddress.getByName("127.0.0.1");
System.out.println(inet3);
//获取本地IP
InetAddress inet4 = InetAddress.getLocalHost();
System.out.println(inet4);
//getHostName():获取域名
System.out.println(inet2.getHostName());
//getHostAddress():获取IP地址
System.out.println(inet2.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
端口号
- 端口号标识正在计算机上运行的进程(程序)
- 不同的进程有不同的端口号
- 被规定为一个16位的整数0~65535
- 端口号与IP地址的组合得出一个网络套接字:Socket
2.3 通信要素2:网络协议
计算机网络中实现通信必须有一些约定,即通信协议,对速率、传输代码、代码结构、传输控制步骤、出错控制等制定标准。
其中传输层中有两个非常重要的协议:
-
传输控制协议TCP:
- 使用TCP协议前,须先建立TCP连接,形成传输数据通道
- 传输前,采用"三次握手"方式,点对点通信,是可靠的
- TCP协议进行通信的两个应用进程:客户端、服务端
- 传输完毕,需释放已建立的连接,采用"四次挥手",开销大
-
用户数据包协议UDP:
- 将数据、源、目的封装成数据包,不需要建立连接
- 每个数据报的大小限制在64K内
- 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
- 发送数据结束时无需释放资源,开销小,速度快
3. TCP网络编程
3.1 TCP举例1
实现:客户端发送信息给服务端,服务端将数据显示在控制台
//导入的包有:import org.junit.Test;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;
public class TCPTest1 {
//客户端
@Test
public void client(){
Socket socket = null;
OutputStream os = null;
try {
//1.创建Socket对象,指明服务器端的IP和端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet,8899);
//2.获取一个输出流,用于输出数据
os = socket.getOutputStream();
//3.写出数据操作
os.write("你好,我是客户端".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源的关闭
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//服务器端
@Test
public void server() {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1.创建服务器端的ServerSocket,指明自己的端口号
ss = new ServerSocket(8899);
//2.调用accept()表示接收来自客户端的socket
socket = ss.accept();
//3.获取数据流
is = socket.getInputStream();
//4.读取输入流中的数据
//使用ByteArrayOutputStream不会导致乱码
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while((len = is.read(buffer)) != -1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(baos != null){
//5.关闭资源
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(ss != null){
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3.2 TCP举例2
实现:客户端发送文件给服务端,服务端将文件显示在保存在本地
//导入的包有:import org.junit.Test;import java.io.*;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;
public class TCPTest2 {
//服务端
@Test
public void client(){
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;
try {
//1.创建套接字,指明IP和端口
socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
//2.创建输出流
os = socket.getOutputStream();
//3.创建输入流读取数据
fis = new FileInputStream(new File("001.png"));
//4.读写操作
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis != null){
//5.关闭资源
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//客户端
@Test
public void server(){
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
//1.创建服务端套接口,指明端口号
ss = new ServerSocket(9090);
//2.获取客户端Socket
socket = ss.accept();
//3.获取客户端输入流
is = socket.getInputStream();
//4.保存资源到本地
fos = new FileOutputStream(new File("002.png"));
//5.读写过程
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
//6.关闭资源
try {
fos.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(ss != null){
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3.3 TCP举例3
实现:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端,并关闭相应的连接
//导入的包有:import org.junit.Test;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStream;
public class TCPTest3 {
//服务端
@Test
public void client(){
//在举例2的基础上添加操作,在第4步读写操作后插入第5步
//5.接收来自于服务器端的数据,并显示到控制台上
//关闭数据的输出
socket.shutdownOutput();
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[20];
int len1;
while((len1 = is.read(buffer)) != -1){
baos.write(buffer,0,len1);
}
System.out.println(baos.toString());
}
//客户端
@Test
public void server(){
//在举例2的基础上添加操作,在第5步读写操作后插入第6步
//6.服务端给予客户端反馈
OutputStream os = socket.getOutputStream();
os.write("你好,我已收到信息".getBytes());
}
}
4. UDP网络编程
实现:发送端发送一段文字给接收端
//导入的包有:import org.junit.Test;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;
public class UDPTest {
//发送端
@Test
public void sender() throws IOException {
DatagramSocket socket = new DatagramSocket();
String str = "我是发送端";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
socket.send(packet);
socket.close();
}
//接收端
@Test
public void receiver() throws IOException {
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
5. URL编程
URL:统一资源定位符,它表示Internet上某一资源的地址。
通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www站点。浏览器通过解析给定的URL可以在网络上查找相应的文件或其他资源。
URL的基本结构由5部分组成: <传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
//导入的包有:import java.net.MalformedURLException;import java.net.URL;
public class URLTest {
public static void main(String[] args) {
try {
URL url = new URL("http://Localhost:8e8e/exampLles/beauty.jpg?username=Tom");
// public String getProtocol( ) 获取该URL的协议名
System.out.println(url.getProtocol());
// public String getHost( ) 获取该URL的主机名
System.out.println(url.getHost());
// public String getPort( ) 获取该URL的端口号
System.out.println(url.getPort());
// public String getPath( ) 获取该URL的文件路径
System.out.println(url.getPath());
// public String getFile( ) 获取该URL的文件名
System.out.println(url.getFile());
// public String getQuery( ) 获取该URL的查询名
System.out.println(url.getQuery());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}