网络编程
1.1 概述
? 1.1.1 连接的两种方式(数据以包的形式进行传输,所以会存在丢包现象,也就是数据可能有损失):
? 1.打电话 - 连接 - 接了 - 通话 TCP
? 2.发短信 - 发完了 - 接收到/没接收到 UDP
? 1.1.2计算机网络:
? 计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及==网络通信协议==的管理和协调下,==实现资源共享==和信息传递的计算机系统。
? 1.1.3网络编程的目的:
? 实现传播信息交流,数据交换,通信。
? 1.1.4如何达到这种效果:
? 1.如何准确的定位网络是的一台主机 局域网:端口号,定位到这个计算机上的某个资源
? 2.找到这台主机该如何传输数据?
1.2 网络通信的要素
如何实现网络通信? ? 通信两方的地址: ? 1.ip 和端口号:IP (将两者用:连起来即可) ? 2.网络通信协议:udp、te 规则:网络通信的协议 都用new来new出想要的对象即可
1.3 IP
ip地址:InetAddress
-
? 唯一定位一台网络上计算机 -
127.0.0.1:本机localhost -
ip地址分类:
-
IPV4/IPV6:
- IPV4:127.0.0.1,由4个字节组成(用.隔开),每个字节可以是0~255
- IPV6:128位,由0123456789abcdef(十六进制)组成,4个整数为一组,用5个:分隔成6组(eg: 2002:abbb:525a:1aaa:bddd:56ab)
-
公网(互联网)- 私网(局域网)
- ABCD类地址
- 192.168.xx.xx,专门给组织内部使用
-
域名:记忆IP问题
IP类的代码实现:InetAddress类
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestIP {
public static void main(String[] args) {
try {
InetAddress inetAddress1 = InetAddress.getByName("localhost");
System.out.println(inetAddress1);
InetAddress inetAddress2 = InetAddress.getLocalHost();
System.out.println(inetAddress2);
InetAddress inetAddress3 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress3);
System.out.println(inetAddress3.getHostAddress());
System.out.println(inetAddress3.getCanonicalHostName());
System.out.println(inetAddress3.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
1.4 端口Port
端口表示计算机上的一个程序进程
- 不同的进程有不同的端口号,用来区分软件
- 被规定0-65535(代表可以跑65535个程序)
- TCP,UDP:65535 * 2,单个协议下,端口号不能冲突,如tcp用80,那udp也能用 80,因为是两个不同的协议。
- 端口分类
- 公有端口 0~1023 - HTTP:80 - HTTPS:443 - FTP:21 - Telent:23
- 程序注册端口:1024~49151,分配用户或者程序
- Tomcat:8080 - MySOL:3306 - Oracle:1521 - 动态、私有:49152~65535 - DOC命令: netatat -ano //查看所有端口 netstat -ano|findstr"5900" //查看指定端口 tasklist|findstr"8696" //查看指定端口进程
端口的代码实现:InetSocketAddress类
import java.net.InetSocketAddress;
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
System.out.println(inetSocketAddress);
System.out.println(inetSocketAddress.getAddress());
System.out.println(inetSocketAddress.getHostName());
System.out.println(inetSocketAddress.getPort());
}
}
1.5通信协议
? 协议:约定,就好比我们现在对话用的是普通话
? 网络通信协议:速率、传输速率、代码结构、传输控制…
? TCP/IP协议簇:实际上是一组协议
? 重要:
- TCP:用户传输协议
- UDP:用户数据协议
? 出了名的协议:
- TCP:传输控制协议
- IP:网络互连协议
? TCP 和 UDP对比
TCP:类比打电话
三次握手(模拟场景):
a:可以和你连接吗
b: 真的想和我连接
a: 对的
//然后才建立连接
四次挥手(模拟场景):
a:我要走了
b:你要走?
b:你真的要走了?
a:对,我真的要走了
//然后才断开连接
UDP:类比发信息
- 不连接,不稳定
- 客户端、服务端:没有明确的界限
- 不管准备好没,都可以发给你
- DDOS:(饱和攻击),类似于短信轰炸,堵住传输路径
1.6 TCP
客户端
- 连接服务器Socket
- 发送信息
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
socket = new Socket(serverIP,port);
os = socket.getOutputStream();
os.write("你好,我是小爱".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服务器
- 建立服务端口ServerSocket
- 等待用户链接accept
- 接收用到的信息
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) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
serverSocket = new ServerSocket(9999);
socket = serverSocket.accept();
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
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){
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();
}
}
}
}
}
文件上传
1.以Socket类对象来作为客户端和服务器端的连接
2.先运行服务端,再让客户端运行,从而连接上去
3.文件传输或者信息的传输都要用到io中的管道流
4.当运行完毕后,包目录下就会有所传输的文件
客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("D:\\Idea\\ideaiu-2019.3.3\\workspace02\\src\\网络编程\\TCP\\1.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while((len = inputStream.read(buffer)) != -1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
服务端
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo02 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("recieve.jpg");
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();
serverSocket.close();
}
}
Tomcat
服务端
- 自定义服务端 S
- Tomcat服务器S: java后台开发
客户端
1.7 UDP
发送信息
服务端:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9000);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
客户端:不需要与服务端建立连接也可以发送
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String msg = "你好,服务器";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9000;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
socket.send(packet);
socket.close();
}
}
聊天(单向聊天)
发送方:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;
public class UdpSenderDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
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("localhost",6666));
socket.send(packet);
if(data.equals("bye")){
break;
}
}
socket.close();
}
}
接收方:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpReceiveDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
while(true) {
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);
byte[] data = packet.getData();
String receivedatas = new String(data, 0, data.length).trim();
System.out.println(receivedatas);
if (receivedatas.equals("bye")) {
break;
}
}
socket.close();
}
}
聊天(互相聊天)
以老师和学生聊天为例(多线程实现):
老师和学生每人都应有一个接收端和发送端
接收信息端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int port;
private String msg;
public TalkReceive(int port,String msg) {
try {
this.port = port;
this.msg = msg;
socket = new DatagramSocket(port);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true) {
try {
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);
byte[] data = packet.getData();
String receivedatas = new String(data, 0, data.length).trim();
System.out.println(msg + ":" + receivedatas);
if (receivedatas.equals("bye")) {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
发送信息端:
io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TalkSend implements Runnable{
DatagramSocket socket = null;
BufferedReader reader = null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
try {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
socket.send(packet);
if(data.equals("bye")){
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
然后是老师和学生的类:
老师:
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(4321,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"学生")).start();
}
}
学生:
public class TalkStu {
public static void main(String[] args) {
new Thread(new TalkSend(1234,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}
即可实现双方的对话:
? 老师:
? 学生:
URL
eg:https://www.baidu.com/
统一资源定位符:定位资源的,定位互联网上的某一个资源
DNS域名解析:将www.xxxx.com转换为xxx.x…x…xx
协议://ip地址:端口/项目名/资源
URL类的基本使用:
import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo01 {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("https://blog.csdn.net/hanpiyo?type=blog");
System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPort());
System.out.println(url.getPath());
System.out.println(url.getFile());
System.out.println(url.getQuery());
}
}
使用URL类下载网络资源:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class UrlDown {
public static void main(String[] args) throws Exception {
URL url = new URL("https://p1.music.126.net/VTZde5VdBm_u2WH0Pc9HQQ==/109951165561227373.jpg?param=130y130");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("109951165561227373.jpg");
byte[] buffer = new byte[1024];
int len;
while((len = inputStream.read(buffer)) != -1){
fos.write(buffer,0,len);
}
fos.close();
inputStream.close();
urlConnection.disconnect();
}
}
下载完之后便会看到所下载好的资源:
|