网络编程

网络编程

1.1、IP

ip地址:InetAddress

  • 唯一定位一台网络上计算机
  • 127.0.0.1 :本机localhost
  • IP地址的分类
    • IPV4、IPV6
    • 公网(互联网)---私网(局域网)
      • ABCD类地址
      • 192.168.xx.xx
//测试IP
public class TestInetAddress {
    public static void main(String[] args)  {
        try {
            //查询本机地址
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress2);
            System.out.println(inetAddress3);

            //查询网站IP地址
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress4);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

1.2、端口

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

  • 不同的进程有不同的端口号,用来区分软件

  • 被规定0~65535

  • 单个协议下,端口号不能冲突

  • 端口分类

    • 公有端口0~1023
      • HTTP : 80
      • HTTPS : 443
      • FTP : 21
      • Telent :23
    • 程序注册端口:1024~49151
      • Tomcat : 8080
      • MySQ : 3306
      • Oracle : 1521
    • 动态、私有 : 49152~65535
    netstat -ano#查看所有端口
    netstat -ano|findstr "8864" #查看指定端口
    

1.3、通信协议

  • TCP

    如打电话,连接,稳定,三次握手、四次挥手

  • UDP

    如发短信,不连接,不稳定

1.4TCP

  • 客户端

​ 1.连接服务器 Socket

​ 2.发送消息

//客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket=null;
        OutputStream os=null;
        try {
            //1.要知道服务器的地址,端口号
            InetAddress address=InetAddress.getByName("127.0.0.1");
            int port=9999;
            //2.创建一个socket连接
            socket=new Socket(address,port);
            //3.发送消息 IO流
            os=socket.getOutputStream();
            os.write("hello,world".getBytes());//哪个????????????????
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } 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();
                }
            }
        }
    }
}
  • 服务器

​ 1.建立服务器端口 ServerSocket

​ 2.等待用户来凝结 accept

​ 3.接收用户消息

//服务器
public class TcpServerDemo01 {
    public static void main(String[] args) {

        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream inputStream=null;
        ByteArrayOutputStream baos=null;
        try {
            //有一个地址
            serverSocket=new ServerSocket(9999);
            System.out.println("服务器已打开,等待客户连接...");
            //等待客户端连接进来
            socket=serverSocket.accept();
            System.out.println("客户连接成功");
            //读取客户端的消息
            inputStream=socket.getInputStream();

            //管道流
            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();
                }
            }
        }
    }
}

文件传输

  • 服务器

    //服务器2  文件上传
    public class TcpServerDemo02 {
        public static void main(String[] args) throws Exception {
            //创建服务器
            ServerSocket serverSocket=new ServerSocket(8888);
    
            System.out.println("服务器已打开,等待客户连接...");
            Socket socket = serverSocket.accept();
            System.out.println("客户连接成功");
    
            //获取输入流
            InputStream inputStream = socket.getInputStream();
    
            //文件输出
            FileOutputStream fos =new FileOutputStream(new File("copy轻音.png"));
            byte[] buffer =new byte[1024];
            int len;
            while((len=inputStream.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
    
            //通知客户端我接受完毕
            OutputStream os=socket.getOutputStream();
            os.write("服务器:我接受完毕,可以断开连接".getBytes());
    
            //关闭资源
            os.close();
            fos.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
        }
    }
    
    
  • 客户端

    //客户端2    文件上传
    public class TcpClientDemo02 {
        public static void main(String[] args) throws IOException {
            //创建Socket连接
            Socket socket=new Socket("127.0.0.1",8888);
            //创建输出流
            OutputStream os=socket.getOutputStream();
            //读文件
            FileInputStream fileInputStream=new FileInputStream("E:\\java123\\study-module\\qingyin.png");//为什么相对路径不行??
            //写文件
            byte[] buffer =new byte[1024];
            int len;
            while((len=fileInputStream.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((len2=inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len2);
            }
            System.out.println(baos.toString());
            //关闭资源
            baos.close();
            inputStream.close();
            fileInputStream.close();
            os.close();
            socket.close();
        }
    }
    
    

1.5 UDP

发送消息

  • 发送端
//不需要连接服务器
public class UdpClientDemo01 {
    public static void main(String[] args) throws IOException {
        //1.建立一个Socket
        DatagramSocket socket=new DatagramSocket();

        //建立一个包
        String msg="hello,world!";
        InetAddress localhost=InetAddress.getByName("localhost");
        int port=9090;
        DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);

        //发送包
        socket.send(packet);

        //关闭流
        socket.close();
    }
}
  • 接收端
public class UdpServerDemo01 {
    public static void main(String[] args) throws IOException {
        //开放端口
        DatagramSocket socket=new DatagramSocket(9090);
        //接收数据包
        byte[] bytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        socket.receive(packet);//阻塞接收

        System.out.println(packet.getAddress());
        System.out.println(new String(packet.getData()));

        //关闭端口
        socket.close();
    }
}

循环发送接收消息

  • 发送端
  public class UdpSenderDemo02 {
    public static void main(String[] args) throws IOException {
        //建立一个Socket
        DatagramSocket socket=new DatagramSocket(8080);
        //从控制台接收发送的消息
        BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
        while (true){
            String msg=reader.readLine();
            //从控制台接收发送的消息
            //Scanner scanner=new Scanner(System.in);
            //String msg=scanner.next();

            DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,new InetSocketAddress("localhost",9090));
            //发送包
            socket.send(packet);
            if (msg.equals("bye"))break;
        }
        //关闭流
        socket.close();
    }
}
  • 接收端
  public class UdpServerDemo02 {
    public static void main(String[] args) throws IOException {
        //开放端口
        DatagramSocket socket=new DatagramSocket(9090);
        while (true){
            //接收数据包
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
            socket.receive(packet);//阻塞接收

            String s = new String(packet.getData(),0,packet.getLength());
            System.out.println(packet.getAddress()+"   "+s);

            //结束判断
            if (s.equals("bye")){
                System.out.println("结束");
                break;
            }
        }
        //关闭端口
        socket.close();
    }
}

多线程在线聊天

  • 发送功能对象
public class TalkSend implements  Runnable{
    DatagramSocket socket=null;
    BufferedReader reader=null;
    private  String toIP;
    private int toport;
    private  int fromport;
    public TalkSend(String toIP, int toport,int fromport) {
        this.toIP = toIP;
        this.toport = toport;
        this.fromport=fromport;
        try {
            socket = new DatagramSocket(fromport);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while (true){
            try {
                String msg=this.reader.readLine();
                byte[] bytes=msg.getBytes();
                DatagramPacket packet=new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress(this.toIP,this.toport));
                //发送包
                socket.send(packet);
                if (msg.equals("bye"))break;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //关闭流
        socket.close();
    }
}

  • 接收功能对象
public class TalkReceive implements Runnable{
    DatagramSocket socket=null;
    private  int port;
    private  int fromport;
    public TalkReceive(int port,int fromport) {
        this.port = port;
        this.fromport=fromport;
        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);//阻塞接收
                String s = new String(packet.getData(),0,packet.getLength());
                System.out.println("from "+fromport+":"+s);
                //结束判断
                if (s.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //关闭端口
        socket.close();
    }
}

  • 用户1
public class TalkStudent {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend("localhost",9999,7777)).start();
        new Thread(new TalkReceive(8888,6666)).start();
    }
}
  • 用户2
public class TalkSomeone {
    public static void main(String[] args) {
        new Thread(new TalkSend("localhost",8888,6666)).start();
        new Thread(new TalkReceive(9999,5000)).start();
    }
}

1.6URL

协议://ip地址:端口/项目名/资源
public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("https://m801.music.126.net/20210818194943/24d72ad156d84de41f049a4f99f8552b/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/10362461644/c455/db10/ba72/cc9aa86a5f35bbd5456531bcd6bdf123.m4a");
        System.out.println(url.getProtocol());//协议
        System.out.println(url.getHost());//主机IP
        System.out.println(url.getPort());//端口
        System.out.println(url.getPath());//文件
        System.out.println(url.getFile());//全路径
        System.out.println(url.getQuery());//参数
    }
}
  • 下载网络资源
public class UrlDown {
    public static void main(String[] args) throws IOException {
        //下载地址
        URL url = new URL("https://m881.music.126.net/20210818194943/24d72ad156d84de41f049a4f99f8552b/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/10362461644/c455/db10/ba72/cc9aa86a5f35bbd5456531bcd6bdf123.m4a");
        
        //连接到这个资源  HTTP
        HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();

        InputStream inputStream=urlConnection.getInputStream();
        FileOutputStream fos=new FileOutputStream("123.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();//断开连接

    }
}
posted @ 2021-08-19 14:58  酷酷丶吖  阅读(31)  评论(0)    收藏  举报