一、概述
- 计算机网络:
计算机网络是指将地理位置不同的具有独立功能的多台计算机及七外部设备,通过通信线路连接起来在网络操作系统、网络管理软件、网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统 - 网页编程:javaweb ,通过B/S架构访问
网络编程:TCP/IP ,通过C/S架构访问
二、网络通信的要素
- 需要双方的地址:
IP , 端口号 - 网络通信的协议(规则):
TCP/IP参考模型:
网络编程重点针对传输层的TCP、UDP
三、IP地址
- ip地址的分类
- ipv4/ipv6:
ipv4:由32位IP地址组成
ipv6:由128位IP地址组成 - ABCD类地址:
A类地址的第一组数字为1~126;B类地址的第一组数字为128~191;C类地址的第一组数字为192~223;D类地址的第一组数字为224~239
- ipv4/ipv6:
//测试IP
public class TestInetAddress {
public static void main(String[] args) {
try {
//查询本机地址
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1);///127.0.0.1
InetAddress inetAddress2 = InetAddress.getByName("localhost");
System.out.println(inetAddress2);//localhost/127.0.0.1
InetAddress inetAddress3 = InetAddress.getLocalHost();
System.out.println(inetAddress3);//LAPTOP-PRU5J1R3/192.168.3.18
//查询网站ip地址
InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress4);//www.baidu.com/183.232.231.172
//常用方法
System.out.println(inetAddress4.getCanonicalHostName());//规范名字 183.232.231.172
System.out.println(inetAddress4.getHostAddress());//ip 183.232.231.172
System.out.println(inetAddress4.getHostName());//域名,或是自己电脑的名字 www.baidu.com
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
四、端口
- 端口表示计算机上的一个进程:
- 不同进程有不同的端口号,用来区分软件
- 规定为:0~65535
- 端口可分为TCP和UDP两种协议(不同协议下端口号可以相同,相同协议下端口号不能相同冲突)
- 端口分类:
- 公有端口:0~1023:
HTTP:80
HTTPS:443
FTP:21
Telent:23 - 程序注册端口:1024~49151 ,分配用户或者程序
Tomcat:8080
MySQL:3306
Oracle:1521 - 动态、私有:49153~65535
- 公有端口:0~1023:
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost", 8080);
System.out.println(inetSocketAddress);// /127.0.0.1:8080
System.out.println(inetSocketAddress2);// localhost/127.0.0.1:8080
System.out.println(inetSocketAddress.getAddress());// /127.0.0.1
System.out.println(inetSocketAddress.getHostName());// 127.0.0.1
System.out.println(inetSocketAddress.getPort());// 8080
}
}
五、通信协议
- TCP/IP协议:
-
其中重要的两个协议:
TCP:用户传输协议
UDP:用户数据报协议 -
其中出名的协议:
TCP
IP:网络互联协议
- TCP与UDP对比:
-
TCP(类似于打电话):
-
连接,稳定
-
三次握手,四次分手:
- 握手:
- A:我要和你连接
- B: 好,连接
- A:好,那连接
- 分手:
- A:我要断开
- B:我了解你要断开了
- B:你断开了吗?
- A:我断开了
- 握手:
-
-
UDP(类似于发短信):
- 不连接,不稳定
- 客户端、服务的没有明确界限
- 无论有没有准备好都能发出
六、TCP
- 实现聊天:
//客户端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os= null;
try {
//1.要知道服务器的地址、端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 666;
//2.创建一个socket连接
socket = new Socket(serverIP,port);
//3.发送消息 IO流
os = socket.getOutputStream();
os.write("hello".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (os!=null) {
os.close();
}
if (socket!=null) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//服务端
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is =null;
ByteArrayOutputStream baos = null;
try {
//1.要创建一个端口
serverSocket = new ServerSocket(666);
//2.等待客户端连接过来
socket = serverSocket.accept();
//3.读取客户端的消息
is = socket.getInputStream();
//管道流
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int temp;
while ((temp=is.read(buffer))!=-1){
baos.write(buffer,0,temp);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (baos!=null){
baos.close();
}
if (is!=null){
is.close();
}
if (socket!=null){
socket.close();
}
if (serverSocket!=null){
serverSocket.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
- TCP实现文件上传
//客户端
public class TcpClientDemo02 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
FileInputStream fis=null;
try {
//1. 创建连接
socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
//2. 创建输出流
os = socket.getOutputStream();
//3.读取文件
fis = new FileInputStream("E:\\idea项目\\IP\\src\\hello");
//4. 写出文件
byte[] buffer = new byte[1024];
int temp ;
while ((temp = fis.read(buffer))!=-1){
os.write(buffer,0,temp);
}
//告诉客户端传输完毕
socket.shutdownOutput();
//确定客户端接收完毕才能断开
InputStream is = socket.getInputStream();
//String byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2=new byte[1024];
int temp2;
while ((temp2=is.read(buffer))!=-1){
baos.write(buffer,0,temp2);
}
System.out.println(baos.toString());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (fis!=null){
fis.close();
}
if (os!=null){
os.close();
}
if (socket!=null){
socket.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
//服务端
public class TcpServerDemo02 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
//1. 创建服务连接
serverSocket = new ServerSocket(9000);
//2. 监听客户端的连接
socket = serverSocket.accept();//阻塞式监听,会一直等待客户端
//3. 创建输入流
is = socket.getInputStream();
//4. 文件输出
fos = new FileOutputStream("E:\\idea项目\\IP\\src\\hi");
byte[] buffer = new byte[1024];
int temp;
while ((temp= is.read(buffer))!=-1){
fos.write(buffer,0,temp);
}
//通知客户端我接收完毕了
OutputStream os = socket.getOutputStream();
os.write("我接收完毕了,可以断开了".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (fos!=null){
fos.close();
}
if (is!=null){
is.close();
}
if (socket!=null){
socket.close();
}
if (serverSocket!=null){
serverSocket.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
- Tomcat
- 服务端:
自定义 ----- S
或
Tomcat服务器 ----- S
- 客户端:
自定义 ----- C
或
浏览器 ----- B
- 服务端:
七、UDP
不需要连接,需要知道对方地址
- 发送消息
//接收端
public class UdpReceiveDemo01 {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
//开放端口
socket = new DatagramSocket(9090);
//接收数据包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);//阻塞接收
System.out.println(new String(packet.getData(),0,packet.getLength()));
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (socket!=null)
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
//发送端
//不需要连接服务器
public class UdpSendDemo01 {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
//1.建立一个Socket
socket = new DatagramSocket();
//2.建一个包
String msg = "hello";
//发送给谁
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
//数据、数据长度,发送给谁
DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
//3.发送包
socket.send(packet);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
//4.关闭流
if (socket!=null)
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
- 实现多线程聊天
public class TalkReceive implements Runnable{
int port;
String name;
public TalkReceive(int port, String name) {
this.port = port;
this.name = name;
}
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(port);
while (true){
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
byte[] data = packet.getData();
String receiveData = new String(data,0,data.length);
System.out.println(name+":"+receiveData);
//断开连接 bye
if (receiveData.equals("bye")){
break;
}
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TalkSend implements Runnable{
int fromPort;
String toIP;
int toPort;
public TalkSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
}
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(fromPort);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(toIP, toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Student {
//开启两个线程
public static void main(String[] args) {
new Thread(new TalkSend(777,"localhost",999)).start();
new Thread(new TalkReceive(888,"老师")).start();
}
}
public class Teacher {
//开启两个线程
public static void main(String[] args) {
new Thread(new TalkSend(555,"localhost",888)).start();
new Thread(new TalkReceive(999,"学生")).start();
}
}
八、URL
- url 叫做统一资源定位符(定位互联网上的某个资源)
协议名 : // ip地址 : 端口 / 项目名 / 资源
URL url = new URL("....");
url.getProtocol(); // 获取协议名
url.getHost();// 获取主机ip
url.getPort();// 获取端口
url.getPath();// 获取文件
url.getFile();// 获取全路径
url.getQuery();// 获取参数
- URL下载网络资源
public class UrlDown {
public static void main(String[] args) throws Exception {
//1.下载地址
URL url = new URL("https://cn.bing.com/images/search?view=detailV2&ccid=NQLL99Yz&id=1C8280D2D75B8653FE4F94F7C32E1B68E30CC400&thid=OIP.NQLL99YzJz3AuHNiQ8C1bwHaEo&mediaurl=https%3a%2f%2fwww.keaidian.com%2fuploads%2fallimg%2f190424%2f24110307_5.jpg&exph=1200&expw=1920&q=%e5%9b%be%e7%89%87&simid=608023354961633793&FORM=IRPRST&ck=57203E8211F35408A25FAEE812A3920C&selectedIndex=0&idpp=overlayview&ajaxhist=0&ajaxserp=0");
//2. 连接到这个资源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("E:\\idea项目\\IP\\src\\a.jpg");
byte[] buffer = new byte[1024];
int temp;
while ((temp = inputStream.read(buffer))!=-1){
fos.write(buffer,0,buffer.length);
}
fos.close();
inputStream.close();
urlConnection.disconnect();//断开连接
}
}