JAVA--网络编程

1.网络编程

1.1 网络编程介绍

小结:

  1. 网络编程中有两个主要的问题
    如何准确定位到网络上的一台或者多台主机
    找到主机之后如何进行通信
  2. 网络编程中的要素
    ip和端口号----通过ip类
    网络通信协议----通过udp和tcp类
  3. 万物皆对象

1.2 IP

ip地址:InetAddress

1. 唯一定位一台网络上的计算机

2. 127.0.0.1 : 本机localhost

3. IP地址的分类
		ipv4/ipv6
			ipv4:127.0.0.1,4个字节组成,0-255
			ipv6:128位,8个无符号整数,例如2001:0bb2:4aa1:1222:4342:5555:222a:333b
		公网(互联网)-私网(局域网)
			ABCD类地址
			192.168.xx.xx专门给组织内部使用的
4.域名:记忆ip问题
		ip:www.vip.com

InetAddress类

package netbiancheng;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestInetAddress {
    public static void main(String[] args) {
        //try-catch快捷键,选中alt+ctrl+T
        try {
            //查询本机地址
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress);
            InetAddress inetAddress3 = InetAddress.getByName("localhost");
            System.out.println(inetAddress3);
            InetAddress inetAddress4 = InetAddress.getLocalHost();
            System.out.println(inetAddress4);

            //查询网站地址
            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());  //ip地址
            System.out.println(inetAddress2.getHostName()); //域名或者自己电脑的名字
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }


    }
}

JAVA--网络编程_第1张图片

1.3 端口

端口表示计算机上一个程序的进程

1.不同的进程有不同的端口号,用来区分软件,一般被规定端口为0-65535。还分为TCP端口和UDP端口,即总端口为65535*2。单个协议下,端口号不能冲突。
2.端口分类
		公有端口0-1023
			HTTP:80
			HTTPS:443
			FTP:21
			SSH:22
			Telent:23
		程序注册端口:1024-49151,分配用户或者程序
			Tomcat:8080
			MySQL:3306
			Oracle:1521
		动态、私有:49152-65535
		netstat -ano //查看所有的端口
		netstat -ano|findstr "5900" //查看指定的端口
		tasklist|findstr “8696” //查看指定端口的进程

端口InetSocketAddress类

package netbiancheng;

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);

        InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost",8080);
        System.out.println(inetSocketAddress2);

        System.out.println(inetSocketAddress.getAddress());
        System.out.println(inetSocketAddress.getHostName());
        System.out.println(inetSocketAddress.getPort());    //获取端口号
    }
}

JAVA--网络编程_第2张图片

1.4 通信协议

协议:约定,就好比我们现在说的普通话
网络通信协议: 速率,传输码率,代码结构,传输控制…
问题: 非常的复杂
大事化小:分层
TCP/IP协议簇:实际上是一组协议
重要的是:TCP:用户传输协议,UDP:用户数据报协议
出名的协议是TCP:用户传输协议,IP:网络互连协议

TCP,UDP对比
TCP:打电话

1.连接,稳定
2.三次握手,四次挥手
		最少需要三次,保证稳定连接
		A:你瞅啥?
		B:瞅你咋地
		A:干一场
		最少需要四次,保证断开
		A:我要走了
		B:你真的要走了吗
		B:你真的真的要走了吗
		A:我真的要走了
3.客户端和服务端是分清界限的
4.传输完成,释放连接,效率低

UDP:发短信

1.不连接,不稳定
2.客户端和服务端没有明确的界限
3.不管有没有准备好,都可以发给你
4.导弹
5.DDOS(洪水攻击,饱和攻击)

1.5 TCP

客户端

1.连接服务器,通过Socket
2.发送消息
package TCP;

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) {
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            //1.要知道服务器的地址,端口
            InetAddress ServerIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //2. 创建一个socket连接
            socket = new Socket(ServerIP, port);
            //3. 发送消息IO流
            outputStream = socket.getOutputStream();
            outputStream.write("hello".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

服务器

1.建立服务的端口,通过ServerSocket
2.等待用户的连接,通过accept
3.接收用户的消息
package TCP;

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){

        Socket accept = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            //1.得先有一个地址
            ServerSocket serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
            accept = serverSocket.accept();
            //3.读取客户端的消息
            inputStream = accept.getInputStream();
            //管道流
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            if((length=inputStream.read(buffer))!=-1){
                byteArrayOutputStream.write(buffer,0,length);
            }
            System.out.println(byteArrayOutputStream.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(byteArrayOutputStream!=null){
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept!=null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

JAVA--网络编程_第3张图片

文件上传

客户端

package TCP;

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 {
        //1.读取服务端ip和端口
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        int port = 9000;
        Socket socket = new Socket(inetAddress, port);
        //2.输出信息
        OutputStream outputStream = socket.getOutputStream();
        //3.读取文件
        FileInputStream fileInputStream = new FileInputStream(new File("1.jpg"));
        //4.将读取的文件写入输出流
        byte[] buffer = new byte[1024];
        int length;
        if((length=fileInputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,length);
        }
        //通知服务器,已经传输完毕
        socket.shutdownOutput();
        //接收服务器发来的结束信息
        InputStream inputStream = socket.getInputStream();
        //管道流,夹在客户端和服务器端输入和输出中间
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int length2;
        if((length2=inputStream.read(buffer2))!=-1){
            byteArrayOutputStream.write(buffer2,0,length2);
        }
        System.out.println(byteArrayOutputStream.toString());

        //5.关闭资源
        byteArrayOutputStream.close();
        inputStream.close();
        fileInputStream.close();
        outputStream.close();
        socket.close();
    }
}

服务器端

package TCP;

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 {
        //1.创建服务
        ServerSocket serversocket = new ServerSocket(9000);
        //2.监听客户端的连接
        Socket socket = serversocket.accept();
        //3.获取输入流
        InputStream inputStream = socket.getInputStream();
        //4.将获得文件输出
        FileOutputStream fileOutputStream = new FileOutputStream("1.jpg");
        byte[] buffer = new byte[1024];
        int length;
        if((length=inputStream.read(buffer))!=-1){
            fileOutputStream.write(buffer,0,length);
        }
        //通知客户端,服务器端已经接收完毕
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("接收完毕".getBytes());


        //5.关闭资源
        outputStream.close();
        fileOutputStream.close();
        inputStream.close();
        socket.close();
    }
}

Tomcat

客户端
	自定义C
	浏览器B
服务端
	自定义S
	Tomcat服务器S:java后台开发
C/S即客户端/服务端,一般是在企业内部,无需网络也可传输
B/S即浏览器/服务器,用的更多

1.6 UDP

发短信:不用连接,需要知道对方的地址

发送端:

package UDP;

import java.net.*;

//不需要连接服务器
//UDP是以发送包的形式传输数据
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1.建立一个Socket
        DatagramSocket 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);
        //4.关闭流
        socket.close();
    }
}

接收端:

package 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(9090);
        //接收数据包
        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()));
        //关闭流
        socket.close();
    }
}

循环发送消息

package Chet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

public class UdpSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(9999);
        //终端输入发送的信息
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            //读取信息
            String msg = reader.readLine();
            //将信息转为字节形式
            byte[] bytes = msg.getBytes();
            //将整个字节都放入数据包中进行传输
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress("localhost", 6666));
            socket.send(packet);
            if (msg.equals("bye")){
                break;
            }

        }
        socket.close();
    }
}

循环接收消息

package Chet;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class UdpReceiveDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);
        while (true){
            //利用缓冲区接收包裹
            byte[] buffer = new byte[1024];
            DatagramPacket packet1 = new DatagramPacket(buffer,0,buffer.length);
            socket.receive(packet1);//阻塞式接收包裹
            //打印出接受到的信息
            String s = new String(packet1.getData());
            System.out.println(s);
            if(s.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

在线咨询,两个人都可以是发送方,也可以是接收方

发送方

package Chet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class TalkSend implements Runnable{
    //1.建立一个Socket
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private int fromIP;
    private String toIP;
    private int toPort;

    public TalkSend(int fromIP, String toIP, int toPort) {
        this.fromIP = fromIP;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(fromIP);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            //读取信息
            String msg = null;
            try {
                msg = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将信息转为字节形式
            byte[] bytes = msg.getBytes();
            //将整个字节都放入数据包中进行传输
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress(toIP,toPort));
            try {
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (msg.equals("bye")){
                break;
            }
        }
    }
}

接收方

package Chet;

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 msgFrom;

    public TalkReceive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            //利用缓冲区接收包裹
            byte[] buffer = new byte[1024];
            DatagramPacket packet1 = new DatagramPacket(buffer,0,buffer.length);
            try {
                socket.receive(packet1);//阻塞式接收包裹
            } catch (IOException e) {
                e.printStackTrace();
            }
            //打印出接受到的信息
            String s = new String(packet1.getData());
            System.out.println(msgFrom+":"+s);
            if(s.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

学生端

package Chet;

public class TalkStudent {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"老师")).start();
    }
}

教师端

package Chet;

public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(6666,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"学生")).start();
    }
}

1.7 URL

你可能感兴趣的:(JAVA-SE-基础)