网络编程
1、概述
地球村:与国外同学交流
信件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SYHuvuAp-1630732695245)(https://raw.githubusercontent.com/keaifafafa/IO/master/img/pic/20210829090950.png)]
1.1 计算机网络
计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。
1.2 网络编程
网络编程最主要的工作就是发送端把信息通过规定好的协议进行组装包,在接收端按照规定好的协议把包进行解析,从而提取出对应的信息,达到通信的目的。
1.3、前提条件
* 如何准确的定位网络上的一台主机(IP地址、端口)
* 找到了这个主机,如何传输数据
JavaWeb:网页编程 B/S
网络编程:TCP C/S
2、网络通信的要素
2.1、网络通信的实现方式
通信双方地址:
* ip地址
* 端口
规则:网络通信协议
* TCP/IP参考协议
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-33Cxni8V-1630732695249)(https://raw.githubusercontent.com/keaifafafa/IO/master/img/pic/20210829140123.gif)]
2.2、万物皆对象
1.网络编程中有两个主要的问题
*如何准确的定位到网络上的一台或多台主机
*找到后主机后如何进行通讯
2.网络编程中的要素
*IP地址和端口号
*网络通信协议
3、IP
IP地址:InetAddress
* 唯一定位一台网络上计算机
* 127.0.0.1:本机localhost
* IP地址的分类
* IPV4/IPB6
* IPV4 127.0.0.1 :4个字节组成,0-255, 42亿 2011年用尽
* IPV6 fe80::6c61:9c78:5c7b:18e9%3(config) 256位, 8个无符号整数
`2001:0bb2:aaaa:0015:0000:0000:1aaa:1312`
* 公网(互联网)- 私网(局域网)
* ABCD类地址
* 192.168.xx.xx 专门给组织内部使用的
* 域名:记忆IP问题!
package com.fafa.Internet.lesson01;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestInetAddress {
public static void main(String[] args) {
try {
InetAddress inetAddress01 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress01);
InetAddress inetAddress02 = InetAddress.getByName("localhost");
System.out.println(inetAddress02);
InetAddress inetAddress03 = InetAddress.getLocalHost();
System.out.println(inetAddress03);
InetAddress inetAddress04 = InetAddress.getByName("192.168.10.12");
InetAddress baiDuIp = InetAddress.getByName("www.baidu.com");
System.out.println(baiDuIp);
System.out.println(baiDuIp.getCanonicalHostName());
System.out.println(baiDuIp.getHostAddress());
System.out.println(inetAddress04.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
4、端口
端口表示计算机上的一个程序的进程;
* 不同的进程有不同的端口号!用来区分软件!
* 单个协议下,端口号不能冲突
* 端口分类
* 公有端口 0 ~ 1023
* HTTP:80
* HTTPS: 443
* FTP:21
* Telent : 23
* 程序注册端口 1024 ~ 49151
* Tomcat: 8080
* MySQL: 3306
* Oracle:1521
* 动态、私有: 49152 ~ 65535
win + R --> DOS 命令
Dos 命令
netstat -ano //查看所有端口
netstat -ano|finderstr "" //查看指定的端口
tasklist|finderstr"10052" //查看指定端口的进程
package com.fafa.Internet.lesson01;
import java.net.InetSocketAddress;
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress socketAddress01 = new InetSocketAddress("120.0.0.1", 8080);
InetSocketAddress socketAddress02 = new InetSocketAddress("localhost", 8080);
System.out.println(socketAddress01);
System.out.println(socketAddress02);
System.out.println(socketAddress01.getAddress());
System.out.println(socketAddress01.getHostName());
System.out.println(socketAddress01.getPort());
}
}
5、通信协议
协议:约定,就好比我们现在说的普通话
网络通信协议:速率,传输码率,代码结构,传输控制……
TCP/IP协议簇(一种协议):
*TCP:用户传输协议
*UDP:用户数据报协议
*IP:网络互连协议
TCP UDP 对比:
TCP:打电话
*连接,稳定
*三次握手,四次挥手
*客户端、服务端
*传输完成、释放连接、效率低
UDP:发短信
*不连接、不稳定
*客户端、服务器:没有明确的界限
*不管有没有准备好,都可以发给你
*导弹
*DDOS:洪水攻击!(饱和攻击)
//三次握手,四次挥手
A:你瞅啥?
B: 瞅你咋地?
A:干一场!
A: 我要走了!
B: 你真的要走了吗?
B: 你真的真的要走了吗?
A:我走了!
6、TCP
6.1、实现聊天
有关socket(插槽)的知识分享:https://www.cnblogs.com/dolphinx/p/3460545.html
ServerSocket
为了使客户可以成功地连接到服务器,服务器必须建立一个ServerSocket对象,该对象通过将客户端的套接字对象和服务端的一个套接字对象连接起来,从而达到连接的目的
客户端(socket对象)socket(IP地址,端口)
服务器:(ServerScoket对象)ServerScoket(端口)用ServerScoket.accpet() 来建立一个和客户端的Socket对象相连接的Socket对象。
服务器端的输出流/输入流的目的地和客户端的输入流/输出流的源刚好相同。
客户端
package com.fafa.Internet.lesson02;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDemo01 {
public static void main(String[] args) {
InetAddress serverIP = null;
Socket socket = null;
OutputStream os = null;
try {
serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
socket = new Socket(serverIP, port);
os = socket.getOutputStream();
os.write("网络编程TCP传输测试,fafa".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();
}
}
}
}
}
服务端
package com.fafa.Internet.lesson02;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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;
OutputStream baos = null;
try {
serverSocket = new ServerSocket(9999);
socket = serverSocket.accept();
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer)) != -1){
baos.write(buffer,0,len);
}
System.out.println(((ByteArrayOutputStream) 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();
}
}
}
}
}
6.2、文件上传
客户端
package com.fafa.Internet.lesson02;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
public class TcpFileClientDemo01 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9900);
OutputStream os = socket.getOutputStream();
File file = new File("self.jpg");
InputStream is = new FileInputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
os.flush();
}
socket.shutdownOutput();
InputStream isRcve = socket.getInputStream();
ByteArrayOutputStream o = new ByteArrayOutputStream();
int len1 = 0;
byte[] flush = new byte[1024];
while((len1 = isRcve.read(flush)) != -1){
o.write(flush,0,len1);
}
System.out.println(o.toString());
o.close();
isRcve.close();
os.close();
is.close();
socket.close();
}
}
服务端
package com.fafa.Internet.lesson02;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpFileServerDemo01 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9900);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("receive.jpg");
int len = 0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
fos.flush();
}
OutputStream os = socket.getOutputStream();
os.write("Server已经成功接受数据,可以断开连接!".getBytes());
os.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
7、UDP
不用连接,需要得到对方的地址
7.1、基本框架
发送端
package com.fafa.Internet.lesson03;
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 = "Hello World";
InetAddress localhost = InetAddress.getByName("192.168.10.12");
int port = 9999;
DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
socket.send(packet);
socket.close();
}
}
服务端
package com.fafa.Internet.lesson03;
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(9999);
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();
}
}
8.2、消息循环发送
客户端(发送端)
package com.fafa.Internet.chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
public class UdpSendDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true){
String msg = reader.readLine();
byte[] msgBytes = msg.getBytes();
DatagramPacket packet = new DatagramPacket(msgBytes, 0, msgBytes.length, new InetSocketAddress("localhost", 8866));
socket.send(packet);
if(msg.equals("exit")){
break;
}
}
socket.close();
}
}
服务端(接收端)
package com.fafa.Internet.chat;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReciverDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8866);
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
byte[] data = packet.getData();
String receive = new String(data,0,packet.getLength());
System.out.println(receive);
if(receive.equals("exit")){
break;
}
}
socket.close();
}
}
8.3、UDP多线程实现在线咨询(简易聊天室)
发送端(线程)
package com.fafa.Internet.chatEach;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
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(this.fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
String msg = reader.readLine();
byte[] msgBytes = msg.getBytes();
DatagramPacket packet = new DatagramPacket(msgBytes, 0, msgBytes.length, new InetSocketAddress(this.toIp, this.toPort));
socket.send(packet);
if (msg.equals("exit")) {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
接收端(线程)
package com.fafa.Internet.chatEach;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkRecive implements Runnable{
DatagramSocket socket = null;
private int port;
private String msgFrom;
public TalkRecive(int port, String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(this.port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
byte[] data = packet.getData();
String receive = new String(data,0,packet.getLength());
System.out.println(this.msgFrom + ":" + receive);
if(receive.equals("exit")){
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
学生端
package com.fafa.Internet.chatEach;
public class Student {
public static void main(String[] args) {
new Thread(new TalkSend(8866,"localhost",6666)).start();
new Thread(new TalkRecive(8888,"王老师")).start();
}
}
教师端
package com.fafa.Internet.chatEach;
public class Teacher {
public static void main(String[] args) {
new Thread(new TalkSend(7799,"localhost",8888)).start();
new Thread(new TalkRecive(6666,"学生小明")).start();
}
}
8、URL
统一资源定位符
协议://ip地址:端口/项目名/资源
package com.fafa.Internet.lesson04;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo01 {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:8080/index.jsp?username=fafa&password=123");
System.out.println(url.getProtocol());
System.out.println(url.getPort());
System.out.println(url.getFile());
System.out.println(url.getHost());
System.out.println(url.getPath());
System.out.println(url.getQuery());
}
}
文件下载
package com.fafa.Internet.lesson04;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLDown {
public static void main(String[] args) throws Exception {
URL url = new URL("https://cf-sycdn.kuwo.cn/3d7513d2d06f6173ac8de0c9a3ad74e7/612b1f9f/resource/n3/2/56/3319193984.mp3");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("星辰入梦.mp3");
int len = 0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
fos.flush();
}
fos.close();
is.close();
urlConnection.disconnect();
}
}
import java.net.URL;
/文件下载(爬虫)/ public class URLDown { public static void main(String[] args) throws Exception { //1、下载地址 URL url = new URL(“https://cf-sycdn.kuwo.cn/3d7513d2d06f6173ac8de0c9a3ad74e7/612b1f9f/resource/n3/2/56/3319193984.mp3”);//一个歌曲的地址 //2、连接到这个资源 HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); InputStream is = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream(“星辰入梦.mp3”); int len = 0; byte[] buffer = new byte[1024]; while((len = is.read(buffer)) != -1){ fos.write(buffer,0,len); fos.flush();//强制刷新 } //关闭资源 fos.close(); is.close(); urlConnection.disconnect(); } }
|