网络编程

1.1 概述

 

    网络编程从大的方面就是说对信息的发送接收。

 

    通过操作相应API调度计算机资源硬件,并且利用管道(网线)进行数据交互的过程。

 

    更为具体的涉及:网络模型、套接字、数据包

1.2 网络通信的要素

  如何实现网络通信?

    通信双方地址 

       1 ip

       2 端口号

    规则:网络通信的协议

    TCP/IP参考模型

    

 1.3 ip

  作用:

    1 唯一定位一台网络计算机

    2 127.0.0.1:本机localhost

    3 ip地址的分类:

        ipv4/ipv6

        公网(互联网)- 私网(局域网)

      4 域名:记忆IP问题

      

package com.guo.Lesson01;

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

public class TestInetAddress {
    public static void main(String[] args) {
        try {
            InetAddress[] InetAddress1 = InetAddress.getAllByName("127.0.0.1");
            System.out.println(InetAddress1);
            InetAddress InetAddress2 = InetAddress.getLocalHost();
            System.out.println(InetAddress2);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

1.4 端口

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

    不同的进程有不同的端口号,端口号不能冲突!用来区分软件

    正常端口号:0~65535

    TCP,UDP:单个协议下的端口不能冲突

    公有端口:0~1023

      HTTP:80

      HTTPS:443

     程序注册端口:1024~49151,分配给用户或程序

    tomcat:8080

     MySql:3306

       Oracle:1521

    动态,私有端口:49151~65532    

netstart -ano #查看所有端口

1.5 通信协议

   TCP:用户传输协议

   UDP:用户数据报协议

   IP:网络互联协议

1.6 TCP

  客户端

    1 连接服务器Socket

    2 发送消息

 

package com.guo.Lesson02;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

//客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //连接服务器地址:端口
            InetAddress[] inetAddress =  InetAddress.getAllByName("127.0.0.1");
            int port = 9999;
            //创建Socket连接
            socket = new Socket(inetAddress[0],port);
            os = socket.getOutputStream();
            os.write("你好,欢迎学习JAVA".getBytes(StandardCharsets.UTF_8));
        } 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();
                }
            }
        }
    }

}

 

 

 

  服务器

    1 建立服务的端口 SeverSocket

    2 等待用户连接 accept

    3 接收消息

 

package com.guo.Lesson02;


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) {
        ServerSocket serversocket = null;
        Socket socket = null;
        ByteArrayOutputStream baos = null;
        InputStream is = null ;
        try {
            //创建地址端口
            serversocket = new ServerSocket(9999);
            socket =  new Socket();
            //等待客户端连接
            socket = serversocket.accept();
            //读取客户端数据 管道流
            is = socket.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer))!=-1){
                baos.write(buffer,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 (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();
                }
            }
        }
    }
}

 1.7 udp

  发送端

 

package com.guo.Lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

//不需要连接服务器
public class UdpClientDemo01 {
    public static void main(String[] args) {
        //1 建立一个socket
        DatagramSocket socket = null;
        //2 建个包
        String msg = "你好啊,服务器!";
        //发送对象
        InetAddress[] localhost = null;
        try {
            socket = new DatagramSocket();
            localhost = InetAddress.getAllByName("localhost");
            int port = 9090;
            DatagramPacket packet = new DatagramPacket(msg.getBytes(StandardCharsets.UTF_8),0,msg.getBytes().length,localhost[0],port);
            //3 发送包
            socket.send(packet);
            //4 关闭流
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

  接收端

package com.guo.Lesson03;

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

//还要等待客户端的连接
public class UdpServerDemo01 {
    public static void main(String[] args) {
        //1 开放端口
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(9090);
            //接收数据包
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length); //接收
            socket.receive(packet);
            System.out.println(new String(packet.getData(),0,packet.getLength()));
            //关闭连接
            socket.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }
}

循环接收消息

package com.guo.Chat;

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

public class UapSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        BufferedReader reader = null ;
        while (true){
            //准备数据,从控制台读取数据System.in
            reader = new BufferedReader(new InputStreamReader(System.in));
            String date = reader.readLine();
            byte[] sendate = date.getBytes();  //需要转化为字节才能传递
            DatagramPacket packet = new DatagramPacket(sendate,0,sendate.length,new InetSocketAddress("localhost",6666));
            socket.send(packet);
            if(date.equals("bye")){
                break;
            }
        }
        socket.close();

    }
}
package com.guo.Chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UapReceiveDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);
            while(true){
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            //阻塞式接收消息
            socket.receive(packet);

            byte[] date = packet.getData();
            String receiveData = new String(date,0,date.length);
            String newData = new String(packet.getData(),0,packet.getLength());
            System.out.println(receiveData);
            //断开连接,跳出循环
            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

在线咨询:

package com.guo.Talk;

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

public class Sender implements Runnable{
    DatagramSocket socket = null;
    BufferedReader reader = null ;
    private  int FromPort ;
    private  String ToIp;
    private  int ToPort;
    //构造函数,开启端口,监测输入信息
    public Sender(int FromPort,String ToIp,int ToPort){
        this.FromPort = FromPort;
        this.ToIp = ToIp;
        this.ToPort = ToPort;
        try {
            socket = new DatagramSocket(FromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                    //准备数据,从控制台读取数据System.in
                    reader = new BufferedReader(new InputStreamReader(System.in));
                    String date = null;
                    date = reader.readLine();
                    byte[] sendate = date.getBytes();  //需要转化为字节才能传递
                    DatagramPacket packet = new DatagramPacket(sendate,0,sendate.length,new InetSocketAddress(this.ToIp,this.ToPort));
                    socket.send(packet);
                    if(date.equals("bye")){
                        break;
                    }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();

    }
}
package com.guo.Talk;

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

public class Receiver implements Runnable {

    DatagramSocket socket = null ;
    byte[] container = new byte[1024];
    private int Port;
    private String name;

    public Receiver (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 {
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                //阻塞式接收消息
                socket.receive(packet);
                byte[] date = packet.getData();
                String receiveData = new String(date,0,date.length);
                String newData = new String(packet.getData(),0,packet.getLength());
                System.out.println(name+":"+newData);
                //断开连接,跳出循环
                if (newData.equals("bye")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
package com.guo.Talk;

public class Student {
    public static void main(String[] args) {
        new Thread(new Sender(5555,"localhost",6666)).start();
        new Thread(new Receiver(7777,"老师")).start();
    }
}
package com.guo.Talk;

public class Teacher {
    public static void main(String[] args) {
        new Thread(new Sender(8888,"localhost",7777)).start();
        new Thread(new Receiver(6666,"学生")).start();
    }
}

  1.7 URL

  统一资源定位符:定位互联网的某一个资源

    DNS 域名解析

    1 协议://ip地址:端口/项目名/资源

posted @ 2021-09-17 15:07  小牛哞哞哞  阅读(71)  评论(0)    收藏  举报