网络编程
- 1.概述
- 2.网络通信要素概述
- 3.通信要素1:IP和端口号
- 3.1IP
- 3.2端口号
- 4.通信要素2:网络协议
- 5.TCP网络编程
- 6.UDP网络编程
- 7.URL编程
1.概述
- Java是 Internet 上的语言,它从语言级上提供了对网络应用程序的支持,程序员能够很容易开发常见的网络应用程序。
- ava提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在 Java 的本机安装系统里,由 JVM 进行控制。并且 Java 实现了一个跨平台的网络库,程序员面对的是一个统一的网络编程环境。
- 计算机网络:
把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源。 - 网络编程的目的:
直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯。 - 网络编程中有两个主要的问题:
- 如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
- 找到主机后如何可靠高效地进行数据传输
2.网络通信要素概述
- IP和端口号
(通信双方地址)
- IP(区分不同的主机)
- 端口号(区分主机上应用程序)
- 网络通信协议
一定的规则(即:网络通信协议。有两套参考模型)
- OSI参考模型:模型过于理想化,未能在因特网上进行广泛推广
- TCP/IP参考模型(或TCP/IP协议):事实上的国际标准。
3.通信要素1:IP和端口号
3.1IP
说明:
- Internet上的计算机(通信实体)的唯一标识
- 在Java中使用InetAddress类代表IP
- IP分类:
- IPV4 和 IPV6
- 分类方式2:公网地址(万维网使用)和私有地址(局域网使用)。192.168.开头的就是私有址址,范围即为192.168.0.0–192.168.255.255,
- 域名:www.baidu.com
- 本地回环地址(hostAddress):127.0.0.1 主机名(hostName):localhost
- 如何实例化InetAddress: 两个方法 getByName(String host) getLocalHost()
两个常用方法:getHostName() getHostAddress()
应用
import java.net.InetAddress;
import java.net.UnknownHostException;
// 6.如何实例化InetAddress: 两个方法 getByName(String host) getLocalHost()
// 两个常用方法:getHostName() getHostAddress()
public class InetAddressTest {
public static void main(String[] args) {
try {
InetAddress inet1 = InetAddress.getByName("127.0.0.1");
System.out.println(inet1);
InetAddress inet2 = InetAddress.getByName("www.baidu.com");
System.out.println(inet2);
InetAddress inet3 = InetAddress.getLocalHost();
System.out.println(inet3);
System.out.println(inet2.getHostName());
System.out.println(inet2.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
3.2端口号
说明
- 端口号标识正在计算机上运行的进程(程序)
- 要求:不同的进程有不同的端口号
- 范围:16 位的整数 0~65535。
- 端口号与IP地址的组合得出一个网络套接字:Socket
4.通信要素2:网络协议
- TCP协议:
- 使用TCP协议前,须先建立TCP连接,形成传输数据通道
- 传输前,采用“三次握手”方式,点对点通信,是可靠的
- TCP协议进行通信的两个应用进程:客户端、服务端。
- 在连接中可进行大数据量的传输
- 传输完毕,需释放已建立的连接,效率低
- UDP协议:
- 将数据、源、目的封装成数据包,不需要建立连接
- 每个数据报的大小限制在64K内 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
- 可以广播发送
- 发送数据结束时无需释放资源,开销小,速度快
5.TCP网络编程
步骤
客户端
1.创建Socket类的对象,指明服务器的ip和端口号
2.获取流用于输出数据
3.读写操作
4.关闭流资源
服务器端
1.创建ServerSocket类的对象,指明自己的端口
2.调用accept()方法表示接受来自客户端的Socket
3.获取流用于输入数据
4.读写操作
5.关闭资源
例题1
1.客户端发送内容给服务端,服务端将内容打印到控制台上。
//客户端
@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("你好,lllllllllllllllllllllll我是客户端!".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.读取输入流的数据
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());
System.out.println("收到了来自:" + socket.getInetAddress().getHostAddress() + "数据!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.关闭资源
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 (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
例题2
2.客户端发送文件给服务端,服务端将文件保存在本地。
//客户端
@Test
public void test1() {
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;
try {
InetAddress inet = InetAddress.getByName("127.0.0.01");
socket = new Socket(inet, 5522);
os = socket.getOutputStream();
fis = new FileInputStream(new File("金智秀.jpg"));
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) {
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 test2() {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
//1.创建服务器端的ServerSocket,指明自己的端口
ss = new ServerSocket(5522);
//2.调用accept()表示接受来自客户端的socket
socket = ss.accept();
//3.获取输入流
is = socket.getInputStream();
fos = new FileOutputStream(new File("金智秀1.jpg"));
//4.读取输入流的数据
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("收到了来自:" + socket.getInetAddress().getHostAddress() + "数据!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.关闭资源
if (fos != null) {
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();
}
}
}
}
6.UDP网络编程
步骤
1. DatagramSocket与DatagramPacket
2. 建立发送端,接收端
3. 建立数据包
4. 调用Socket的发送、接收方法
5. 关闭Socket
说明
1. 类 DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序。
2. UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证
UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。
3. DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP
地址和端口号以及接收端的IP地址和端口号。
4. UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和
接收方的连接。如同发快递包裹一样。
//异常应写为:try- catch-finally
import org.junit.Test;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
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();
}
}
7.URL编程
URL网络编程
1.URl:统一资源定位符,对应着互联网的某一资源地址
2.格式:
协议://主机名:端口号/资源地址
<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
例如:
http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
3.常用方法:
public String getProtocol( ) 获取该URL的协议名
public String getHost( ) 获取该URL的主机名
public String getPort( ) 获取该URL的端口号
public String getPath( ) 获取该URL的文件路径
public String getFile( ) 获取该URL的文件名
public String getQuery( ) 获取该URL的查询名
说明
为了表示URL,java.net 中实现了类 URL。我们可以通过下面的构造器来初始化一个 URL 对象:
public URL (String spec):通过一个表示URL地址的字符串可以构造一个URL对象。例如:URL url = new URL ("http://www. atguigu.com/");
public URL(URL context, String spec):通过基 URL 和相对 URL 构造一个 URL 对象。例如:URL downloadUrl = new URL(url, “download.html")
public URL(String protocol, String host, String file); 例如:new URL("http", "www.atguigu.com", “download. html");
public URL(String protocol, String host, int port, String file); 例如: URL gamelan = new URL("http", "www.atguigu.com", 80, “download.html");
URL类的构造器都声明抛出非运行时异常,必须要对这一异常进行处理,通常是用 try-catch 语句进行捕获。
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/examples/beauty.jpgg?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();
}
}
}
URL实现Tomcat服务端数据下载
-- 步骤没有错误
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 URLTest1 {
public static void main(String[] args) {
HttpURLConnection urlConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL("http://localhost:8080/王冰冰/王冰冰.jpg");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
fos = new FileOutputStream("王冰冰1.jpg");
byte[] buffer = new byte[10];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
} 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();
}
}
}
}