网络编程
网络编程概述
Java实现了一个跨平台的网络库,程序员面对的是一个统一的网络编程环境
计算机网络
把分布在不同地理区域的计算与专门的外部设备用通信线路互联成一个规模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源
网络编程地目的
直接或间接地通过网络协议与其他计算机实现数据交换,进行通讯
网络编程中两个主要的问题
- 如何准确地定位网络上一台或多台主机:定位主机上地特定地应用
- 找到主机后如何可靠高效地进行数据传输
网络通信要素概述
通信双方地址
- IP:定位主机
- 端口号:定位主机上某一个应用地进程
一定的规则(即:网络通信协议。有两套参考模型)
- OIS参考模型:模型过于理想化,未能在因特网上进行广泛推广
- TCP/IP参考模型(或TCP/IP协议):事实上的国际标准
通信要素1:IP和端口号
IP地址
- 1、计算机在网络上的唯一标识
- 2、在Java中使用InetAddress类代表IP,new一个对象代表一个IP
- 3、分类:IPV4和IPV6;万维网和局域网
- 4、域名
- 5、本地回路地址:127.0.0.1 对应着:localhost
- 6、实例化InetAddress,并调用其中两个方法:getByName(String host)、getLocalHost(String host)。
两个常用方法:getHostName()/getHostAddress()
InetAddress inet1 = InetAddress.getByName("192.168.10.14");
System.out.println(inet1);
InetAddress inet2 = InetAddress.getByName("www.vip.com");
System.out.println(inet2);
InetAddress inet3 = InetAddress.getByName("127.0.0.1");
System.out.println(inet3);
//获取本地ip
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
System.out.println(inet2.getHostName());//获取主机域名
System.out.println(inet2.getHostAddress());//获取主机IP地址
端口号
- 标识正在计算机上运行的进程(程序)
端口号与IP地址组合得出一个网络套接字:Socket
通信要素2:网络协议
传输层协议中有两个非常重要的协议:
- 传输控制协议TCP
- 用户数据报协议UDP
TCP/IP协议是两个主要的协议而得名:传输层的传输控制协议
(TCP)和网络层的网络互联协议
(IP)
TCP网络编程
TCP协议:
- 使用TCP协议前,必须建立TCP连接,形成传输数据通道
- 传输前,采用“三次握手”方式,点对点通信,
是可靠的
- TCP协议进行通信的两个
应用进程
:客户端、服务端 - 在连接中可
进行大数据量的传输
- 传输完毕,需
释放已建立的连接,效率低
Java实现TCP的网络编程
例子一:客户端发送内容给服务端,服务端将内容打印到控制台上
//客户端
@Test
public void client(){
Socket socket = null;
OutputStream os = null;
try {
//1.创建一个socket,指明服务器端的IP地址和端口号
InetAddress inet = InetAddress.getByName("127.0.01");
//服务器的IP地址和应用程序的端口号
socket = new Socket(inet,8889);
//2.获取一个输出流,用于输出数据
os = socket.getOutputStream();
//3.写出数据
os.write("你好,我是客户端".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//4.关闭资源
try {
if(os != null)
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if(socket != null)
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//服务端
@Test
public void server(){
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos=null;
ServerSocket ss = null;
try {
//1.创建服务器端的ServerSocket,指明自己的端口号
ss = new ServerSocket(8889);
//2.调用accept()方法表示接收来自于客户端的socket
socket = ss.accept();
//3.获取输入流中的数据
is = socket.getInputStream();
//有中文,可能会出现乱码
// byte[] buffer = new byte[20];
// int len;
// while((len = is.read(buffer)) != -1){
// String str = new String(buffer,0,len);
// System.out.println(str);
// }
//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) {
throw new RuntimeException(e);
} finally {
//5.关闭资源
try {
if(is != null)
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if(socket != null)
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if(baos != null)
baos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if(ss != null)
ss.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
例子二:客户端发送文件给服务端,服务端将文件保存在本地
/**
*
* 客户端发送文件给服务端,服务端将文件保存在本地
*
* 此处所有异常该使用try-catch-finally
*
* @author LawrenceLan
* @create 2022--09--29--22:37
*/
public class TCPTest2 {
@Test
public void client() throws IOException {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("****.png"));
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
fis.close();
os.close();
socket.close();
}
@Test
public void server() throws IOException {
ServerSocket ss = new ServerSocket(9000);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\***\\Desktop\\****.png"));
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
socket.close();
ss.close();
}
}
例子三:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。并关闭相应的连接。
**
* 从客户端发送文件给服务端,
* 服务端保存到本地。并返回“发送成功”给客户端。并关闭相应的连接。
* @author LawrenceLan
* @create 2022--09--29--22:49
*/
public class TCPTest3 {
@Test
public void client() throws IOException {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9001);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("****.png"));
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
//关闭数据的输出,接收端才能知道,一个文件传输完成
socket.shutdownOutput();
//接收服务器端发送来的信息
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer1 = new byte[20];
int len1;
while((len1 = is.read(buffer1)) != -1){
baos.write(buffer1,0,len1);
}
System.out.println(baos.toString());
fis.close();
os.close();
socket.close();
is.close();
baos.close();
}
@Test
public void server() throws IOException {
ServerSocket ss = new ServerSocket(9001);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\***\\Desktop\\****.png"));
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
//服务器发送消息给客户端反馈
OutputStream os = socket.getOutputStream();
os.write("你好,照片已经收到".getBytes());
fos.close();
is.close();
socket.close();
ss.close();
os.close();
}
}
客户端—服务端
客户端
- 自定义
- 浏览器
服务端
- 自定义
- Tomcat服务器
UDP网络编程
UDP协议:
- 将数据、源、目的封装成数据包,
不需要建立连接
- 每个数据报的大小限制在64K内
- 发送不管对方是否准备好,接收方收到也不确认,故
是不可靠的
- 可以广播发送
- 发送数据结束时
无需释放资源,开销小,速度快
UDP网络编程示例
/**
*
* UDP协议的网络编程
* @author LawrenceLan
* @create 2022--09--29--23:06
*/
public class UDPTest {
@Test
public void sender() throws IOException {
DatagramSocket socket = new DatagramSocket();
String str="我是UDP方式发送的导弹";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9002);
socket.send(packet);
socket.close();
}
@Test
public void receiver() throws IOException {
DatagramSocket socket = new DatagramSocket(9002);
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();
}
}
URL编程
- 1、URL(Uniform Resource Locator):统一资源定位符,它表示Internet上某一资源的地址
- 2、格式:
http://localhost:8080/examples/beauty.jpg?username=Tom
协议 - 主机名-- 端口号 ----- 资 源 地 址--------参数列表
从本地服务器下载图片到指定位置的示例
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/examples/****.png");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
fos = new FileOutputStream("day10\\****.png");
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 {
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
if(urlConnection != null)
urlConnection.disconnect();
}
}
}