网络编程
计算机网络
- 计算机网络是指地理位置不同的具有独立功能的多台计算机及其外部设备,通过线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。
网络编程的目的
- 传播交流信息,数据交换,通信
想要达到这个效果需要什么:
- 如何准确的定位网络上的一台主机 192.168.16.124 端口,定位到这个计算机上的某个资源
- 找到了这个主机,如何传输数据呢?
网络通信的要素
如何实现网络通信?
通信双方地址:
- ip
- 端口号
- 192.168.16.124:5900
规则:网络通信的协议
小结:
- 网络编程中有两个主要的问题
- 如何准确的定位到网络上的一台或多台主机
- 找到主机后如何进行通信
- 网络编程中的要素
- 找到 IP 和 端口号
- 网络通信协议
IP
- IP 地址:InetAddress类
- 唯一定位一台网络上计算机
- 127.0.0.1:本机locallhost
- IP 地址的分类:
- 通过IP地址分类(ipv4 、 ipv6)
- IPV4 127.0.0.1,四个字节组成,0~255,一共42亿个;30亿在北美,亚洲4亿。2011年就用尽了;
- IPV6 fe80::d16:be1f:c91a:b76d%11,128位,8个无符号整数
- 通过公网(互联网)- 私网(局域网)分类
- 192.168.xx.xx,专门给组织内部使用的
- 通过IP地址分类(ipv4 、 ipv6)
- 域名:记忆IP问题!
//测试IP
public class TestInetAddress {
public static void main(String[] args) {
try {
//查询本机地址
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1.toString());
InetAddress inetAddress3 = InetAddress.getByName("localhost");
System.out.println(inetAddress3.toString());
InetAddress inetAddress4 = InetAddress.getLocalHost();
System.out.println(inetAddress4.toString());
//查询网站ip地址
InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress2);
//常用方法(了解)
//System.out.println(inetAddress2.getAddress());
System.out.println(inetAddress2.getCanonicalHostName());
System.out.println(inetAddress2.getHostAddress());
System.out.println(inetAddress2.getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
端口
- 端口表示计算机上的一个程序的进程
- 不同的进程有不同的端口号!用来区分软件!
- 被规定 0~65535
- TCP / UDP;65535*2,tcp中有80,udp中也可以有80 这个端口,在单个协议下,端口号不能冲突
- 端口分类:
- 公有端口 0~1023
- HTTPS:443
- FTP:21
- Telent:23
- 程序注册端口:1014~49151,这些端口分配给用户或者程序用
- Tomcat :8080
- MySQL :3306
- Oracle :1521
- 动态,私有:49152~65535
- 命令行查看所有端口:netstat -ano
- 公有端口 0~1023
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8000);
InetSocketAddress socketAddress2 = new InetSocketAddress("localhost", 8000);
System.out.println(socketAddress);
System.out.println(socketAddress2);
System.out.println(socketAddress.getAddress());
System.out.println(socketAddress.getHostName());//地址
System.out.println(socketAddress.getPort());//获取端口号
}
}
通信协议
-
协议:约定,
-
网络通信协议
-
TCP/IP协议簇
-
重要的协议:
- TCP:用户传输协议
- UDP:用户数据报协议
-
出名的协议:
- TCP:用户传输协议
- IP:网络互联协议
-
-
TCP UDP 对比
- TCP :连接打电话
- 需要一直连接,稳定
- 三次握手,四次挥手
- 客户端,服务端,有明确的界限
- UDP :不连接发短信
- 不需要一直连接,不稳定
- 客户端,服务端,没有明确的界限
- TCP :连接打电话
TCP
客户端
- 连接服务器 Socket
- 发送消息
//客户端
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");
//2.端口号
int port = 9999;
//3.创建一个socket连接
socket = new Socket(serverIP,port);
//4.发送消息
os = socket.getOutputStream();
os.write("你好,欢迎学习Java".getBytes());
} catch (IOException 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
- 接收用户的消息
//服务端
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream baos = null;
try {
//1.需要有一个地址让客户端连接(地址为localhost,9999)
serverSocket = new ServerSocket(9999);
//2.等待客户端连接过来
socket = serverSocket.accept();
//3.读取客户端的消息
inputStream = socket.getInputStream();
/* 这里对于中文会有乱码
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes))!=-1){
String s = new String(bytes, 0, len);
System.out.print(s);
}
*/
//换一种方式(管道流):
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;
//先将内容读进去
while ((len = inputStream.read(bytes))!=-1){
//再将内容一直向外写
baos.write(bytes,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 (inputStream!=null){
try {
inputStream.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();
}
}
}
}
}
文件上传
- 服务器端
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(new File("第三次用到的图片.jpg"));
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
//要通知客户端我接收完毕了
OutputStream os = socket.getOutputStream();
os.write("我接收完毕了,你可以断开了".getBytes());
} 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 (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 客户端
public class TcpClientDemo02 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
InputStream is = null;
try {
//1.创建一个Socket连接
socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//2.创建一个输出流
os = socket.getOutputStream();
//3.读取文件
fis = new FileInputStream(new File("Java高级\\2021-07-17_104603.jpg"));
//4.写出文件
byte[] bytes = new byte[1024];
int len;
while ((len =fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
//通知服务器,我已经结束了
socket.shutdownOutput();//我已经传输完了
//确定服务器接收完毕,才能断开连接
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] bytes1 = new byte[20];
int len1;
while ((len1 = is.read(bytes1))!=-1){
baos.write(bytes1,0,len1);
}
System.out.println(baos);
} catch (IOException e) {
e.printStackTrace();
} finally {//5.关闭资源
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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();
}
}
}
}
}
UDP
- 发送消息:不需要一直连接,但需要知道地址。
//不需要连接服务器
public class UdpClientDemo01 {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
//1.建立一个Socket
socket = new DatagramSocket();
//2.建个包
String msg = "你好,服务器!";
//发送给谁
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 (IOException e) {
e.printStackTrace();
} finally {
if (socket!=null){
//4.关闭流
socket.close();
}
}
}
}
- 接收消息端
//还是要等待客户端的连接
public class UdpServerDemo01 {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
//开放端口
socket = new DatagramSocket(9090);
//接收数据(包)
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);//接收
socket.receive(packet);//阻塞接收
//输出
System.out.println(new String(packet.getData(),0,packet.getLength()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket!=null){
//关闭连接
socket.close();
}
}
}
}
- 循环发消息
//发送
public class UdpRecriveDemo01 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8888);
//准备数据:要聊天所以要从控制台读取:System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
String str = reader.readLine();//读取一行
byte[] bytes = str.getBytes();//转化成字节数组才能够传输
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress("localhost",6666));//需要数据
socket.send(packet);//发送
//判断是否关掉
if(str.equals("bye")){
break;
}
}
socket.close();
}
}
- 一直接收消息
public class UdpSenderDemo01 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(6666);
while (true){
//准备接收数据
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
socket.receive(packet);//阻塞式接收包裹
//读出数据,判断是否断开连接
byte[] data = packet.getData();
String str = new String(data, 0, bytes.length);
System.out.println(str);
if (str.equals("bye")){
break;
}
}
socket.close();
}
}
- 两个人都可以是发送方,也都可以是接收方:
发送:
public class TalkSend implements Runnable{
DatagramSocket socket = null;
BufferedReader reader = null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSend(){
}
public TalkSend( int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
//准备数据:要聊天所以要从控制台读取:System.in
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {//这里面发消息
while (true){
try {
String str = reader.readLine();//读取一行
byte[] bytes = str.getBytes();//转化成字节数组才能够传输
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress(toIP,toPort));//需要数据加上地址
socket.send(packet);//发送
//判断是否关掉
if(str.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
接收:
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int port;
private String name;
public TalkReceive(int port,String name) {
this.port = port;
this.name = name;
try {
socket = new DatagramSocket(port);//开启连接
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
//准备接收数据
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
socket.receive(packet);//阻塞式接收包裹
//读出数据,判断是否断开连接
byte[] data = packet.getData();
String str = new String(data, 0, bytes.length);
System.out.println(name +":"+ str);
if (str.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
- 测试:
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}
public class TalkTeacher {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(5555,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"学生")).start();
}
}
URL
https://www.baidu.com/
-
url:统一资源定位符;定位资源的;定位互联网上的某一资源。
- 一般url组成:协议://ip地址:端口/项目名/资源
-
DNS域名解析:将一个域名解析成一个IP
public class UrlDown {
public static void main(String[] args) throws IOException {
//1.下载地址
URL url = new URL("https://m701.music.126.net/20210722183648/6eac211be7746de76fb8169d1fca3da0/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/9871844902/10f0/760a/0a3c/c7077443ae3cfb37686b5ca98b678032.m4a");
//2.连接到这个资源 HTTP
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("还是劈开.m4a");
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes))!=-1){
fos.write(bytes,0,len);//写出数据
}
fos.close();
inputStream.close();
urlConnection.disconnect();//断开连接
}
}