网络编程详解

1.IP

package wangluobiancheng;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class InterAddress {
        public static void main(String[] args) {
                    try {
                        InetAddress inetAddress = InetAddress.getLocalHost();
                        System.out.println(inetAddress);
                        InetAddress inetAddress1 = InetAddress.getByName("www.baidu.com");
                        System.out.println(inetAddress1);

                        //常用方法
                        System.out.println(inetAddress1.getAddress());//byte数组形式的IP地址
                        System.out.println(inetAddress1.getCanonicalHostName());//获得规范名
                        System.out.println(inetAddress1.getHostAddress());//ip
                        System.out.println(inetAddress1.getHostName());//域名,或者自己电脑的名字


                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
}

2.端口

概念:表示计算机上的一个程序的进程
1.不同的进程有不同的端口号,用来区分软件
2.被规定0~65535
3.TCP\TDP:65535*2,UDP:80,单个协议下,端口号不能冲突
4.端口分类:
公有端口:0-1023:
HTTP:80
HTTPS:443
FTP:21
Telent:23
程序注册端口:1014–49151,分配用户或者程序
Tomcat:8080;
Mysql:3306;
Oracle:1521;
动态、私有49152~65535

package wangluobiancheng;

import java.net.InetSocketAddress;

public class Demo02InetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress=new InetSocketAddress("127.0.0.1",8080);
        InetSocketAddress inetSocketAddress2=new InetSocketAddress("127.0.0.1",8080);
        System.out.println(inetSocketAddress2);
        System.out.println(inetSocketAddress);


        System.out.println(inetSocketAddress.getAddress());
        System.out.println(inetSocketAddress.getHostName());//地址
        System.out.println(inetSocketAddress.getPort());//端口


    }
}

通信协议

3.TCP

先运行服务端、再运行客户端

客户端

package wangluobiancheng;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/*客户端
* */
public class Demo03TcpClient1 {
    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("你好,欢迎你".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();
                }
            }
        }
    }
}

服务端

package wangluobiancheng;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class Demo04TcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream inputStream=null;
        ByteArrayOutputStream byteArrayOutputStream=null;
        try {
            //1.我得有一个地址
             serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
             socket = serverSocket.accept();
            //3.读取客户端的消息
             inputStream = socket.getInputStream();

            //管道流
             byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int a;
            while ((a=inputStream.read(bytes))!=-1){
                byteArrayOutputStream.write(bytes,0,a);
            }
            System.out.println(byteArrayOutputStream);


        } 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 (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

TCP文件上传实现

客户端

package wangluobiancheng;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/*文件客户端
* */
public class Demo05TcpClient2 {
    public static void main(String[] args) {
        //1.创建一个Socket连接
        try {
            //1.创建一个socket连接
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
            //2.创建一个输出流
            OutputStream outputStream = socket.getOutputStream();
            //3.读取文件
            FileInputStream fileInputStream = new FileInputStream(new File("fengjing.jpg"));
            //4.写出文件
            byte[] bytes = new byte[1024];
            int len;
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            //通知服务器,我已经传输完了
            

            //确定服务器接收完毕,才可以断开连接



            socket.close();
            fileInputStream.close();
            outputStream.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务端

package wangluobiancheng;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*文件服务端

* */
public class Demo06Server2 {
    public static void main(String[] args) {

        try {
            //1.创建服务
            ServerSocket serverSocket = new ServerSocket(9000);
            //2.监听客户端的连接
            Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端连接
            //3.获取文件输入流
            InputStream inputStream = socket.getInputStream();
            //4.文件输出
            FileOutputStream fileOutputStream = new FileOutputStream(new File("receive.jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len=inputStream.read(bytes))!=-1){
                fileOutputStream.write(bytes,0,len);
            }

            //通知客户端我接收完毕了

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

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

初识Tomcat

官网下载,然后在bin目录下的starup,在自己浏览器里面输入8080,就是tomcat的原始ip
注意点:
需要先开启服务器,关闭服务器浏览器不显示
本地IDEA如果有创建好port端口,那Tomcat如果和它重复就会不显示,相反也是一样的,总之本地不能重复端口

UDP发送消息

客户端

package wangluobiancheng;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Demo07UdpClient {
    public static void main(String[] args) throws Exception {
        
        //3.发送给谁
   
            //1.建立一个Socket
            DatagramSocket datagramSocket = new DatagramSocket();
            //2.建一个包
            String msg="第三次";
            InetAddress localhost = InetAddress.getByName("localhost");
            int port=9090;
            //数据、数据的起始、要发送给谁、发送的端口
            DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
            //4.发送数据
            datagramSocket.send(datagramPacket);
            //5.关闭流
            datagramSocket.close();

        }

    }


服务端

package wangluobiancheng;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Demo08UdpServer {
    public static void main(String[] args) throws Exception {
        //1.开放端口
        DatagramSocket datagramSocket = new DatagramSocket(9090);
        //2.接受数据(接收包)
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);//接收

        datagramSocket.receive(datagramPacket);//阻塞接收

        System.out.println(datagramPacket.getAddress().getHostAddress());
        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));

        //3.关闭连接
        datagramSocket.close();


    }
}

UDP实现聊天

发送方

package wangluobiancheng;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class Demo09Sender {
    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket();
        //给包准备数据:控制台读取System.in
        while (true){
            byte[] datas = new BufferedReader(new InputStreamReader(System.in)).readLine().getBytes(StandardCharsets.UTF_8);

            DatagramPacket datagramPacket = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));

            datagramSocket.send(datagramPacket);
            if (datas.equals("bye")){
                break;
            }
        }
        datagramSocket.close();

    }
}

接收方

package wangluobiancheng;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Demo10Receiver {
    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket(6666);

        //循环接收包裹
        while (true){

            //准备接收包裹
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
            datagramSocket.receive(datagramPacket);//阻塞式接收包裹
            //把包化成byte类型
            byte[] data = datagramPacket.getData();
            String data1 = new String(data, 0, data.length);

            System.out.println(data1);
            if (data1.equals("bye")){
                break;
            }


        }
        datagramSocket.close();

    }
}
/*
* 用soker去接收data包,然后再用包的getdata方法获取,再new String转化成字符串
* 判断当有bye字符的时候退出
*
* */

Udp多线程在线咨询

发送端线程准备

package wangluobiancheng;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class Demo11TalkSend implements Runnable{
    DatagramSocket datagramSocket=null;
    BufferedReader bufferedReader=null;

    private int fromPort;
    private int toPort;
    private String toIp;

    public Demo11TalkSend(int fromPort, int toPort, String toIp) {
        this.fromPort = fromPort;
        this.toPort = toPort;
        this.toIp = toIp;

        try {
            datagramSocket = new DatagramSocket(fromPort);
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        } catch (SocketException e) {
            e.printStackTrace();
        }

    }




    @Override
    public void run() {
        while (true){
            try{
                String data= bufferedReader.readLine();
                byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
                DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress(this.toIp,this.toPort));

                datagramSocket.send(datagramPacket);
                if (data.equals("bye")){
                    break;
                }


            }catch (Exception e){
                e.printStackTrace();
            }



        }




    }
}

接收端线程准备

package wangluobiancheng;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Demo12TalkReceive implements Runnable{
    DatagramSocket datagramSocket=null;
    private int port;
    private String  msfrom;

    public Demo12TalkReceive(int port,String msfrom) {
        this.port = port;
        this.msfrom=msfrom;
        try {
            datagramSocket=new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }



    }

    @Override
    public void run() {

        while (true){

            try {
                //准备接收包裹
                byte[] bytes = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
                datagramSocket.receive(datagramPacket);//阻塞式接收包裹
                //把包化成byte类型
                byte[] data = datagramPacket.getData();
                String data1 = new String(data, 0, data.length);

                System.out.println(msfrom+":"+data1);//这样就知道是谁发来的消息
                if (data1.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }


        }

    }
}

老师对话测试

package wangluobiancheng;

public class Demo14Teacher {
    public static void main(String[] args) {
        new Thread(new Demo11TalkSend(1004,1003,"localhost")).start();
        new Thread(new Demo12TalkReceive(1002,"学生")).start();

    }
}


学生对话测试

package wangluobiancheng;
/*只需要知道对方的端口即可,自己的端口不影响收发
*
* */
public class Demo13TalkStudent {
    public static void main(String[] args) {
        new Thread(new Demo11TalkSend(1001,1002,"localhost")).start();
        new Thread(new Demo12TalkReceive(1003,"老师")).start();
    }
}

URL下载网络资源

https://www.baidu.com/
URL:统一资源定位符,定位资源的,定位互联网上的某一个资源
DNS域名解析:https://www.baidu.com/——xxx.x.x.x.x.x.
协议://ip地址:端口/项目名/资源——可以少但是不能多

注意点:去谷歌浏览器检查元素、network,然后找到media,记得先打开播放才会有文件显示出来

package wangluobiancheng;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Demo16UrlDown {
    public static void main(String[] args) throws Exception {
        //1.下载地址
        URL url = new URL("https://m701.music.126.net/20220205025828/7ddb244fcc4394dd94e40143f6ed7765/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/12893442019/456b/f478/1ccb/5ff35d4695f6ac12cd0207eec602988e.m4a");
        //2.连接到这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        //3.获得连接的输入流
        InputStream inputStream = urlConnection.getInputStream();

        //4.连接完毕,对接好输出文件的创建,最后把数据写到输出流里面就可以
        FileOutputStream fileOutputStream = new FileOutputStream("e.m4a");

        //写出这个数据
        byte[] bytes = new byte[1024];
        int len;
        while ((len=inputStream.read(bytes))!=-1){
            fileOutputStream.write(bytes,0,len);
        }
        //5.关闭资源
        inputStream.close();
        fileOutputStream.close();
        urlConnection.disconnect();

    }
}

你可能感兴趣的:(基础学习,网络,java,数据库)