Java---网络编程基础

一、网络编程

1.1概述

打电话–连接–接了—通话 TCP
发短信–发送了就完事了–接收UDP

  • 计算机网络:

计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统网络管理软件网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。

1.2网络通信要素

如何实现网络的通信?
通讯双方地址:IP 、端口

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

规则:网络通讯的协议
七层模型在这里插入图片描述

TCP/IP参考模型:
在这里插入图片描述

1.3IP

IP地址:InetAddress

  • 计算机在Internet上唯一的标识
  • 127.0.0.1:本机locallhost
  • ip地址分类

IPV6/IPV4
ipv4 127.0.0.1,四个字节组成,0~255,42亿,2011亚洲4亿用完;
ipv6:128位,8个无符号整数
2001:0bb2:aaaa:0001:0000:0000:1aaa:1216!
公网(互联网)–私网(局域网)

  • ABCD类地址
  • 192.168.xx.xx,专门给组织内部使用

代码实现查询:

/*
*IP查询和测试的一些方法
*/
import java.net. InetAddress;
import java.net. UnknownHostException;//测试IP
public class TestInetAddress {
    public static void main( string[ ] args) {
        try {
        //查询本机地址
        InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");system.out.println(inetAddress1);
        InetAddress inetAddress3 =InetAddress.getByName("1ocalhost");System.out.print1n( inetAddress3);
        InetAddress inetAddress4 =InetAddress.getLocalHost();system.out.print1n(inetAddress4);
        //查询网站ip地址
        InetAddress inetAddress2 = InetAddress.getByName( "www.baidu.com");system.out.print1n( 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();
        }
    }
}

1.4端口

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

  • 不同进程有不同端口号,用来区分软件的!
  • 被规定为0~65535
  • TCP,UDP:65535*2,tcp:80,udp80,单个协议下,端口不能冲突
  • 端口分类
    • 公有端口 0~1023
    • HTTP:80
    • HTTPS:443
    • FTP:21
    • Telent:23
      • 程序注册端口:1024~49151,分配用户或者程序
    • Tomcat:8080;MySQL:3306;Oracle:1521
    • 动态端口,私有端口:49152~65535
      netstat-nao //查看所有端口
      netstat-nao | findstr//查看指定端口
      tasklist | finder “8696” //查看指定端口进程

1.5 通信协议

网络通信协议:速率,传输码率,代码结构,传输控制…
问题:非常复杂---->分层
TCP/IP协议簇(实质上是一组协议)
重要的:

  • TCP:用户传输协议
  • UDP:用户数据报协议
    出名的TCP,IP:网络互连协议

TCP UDP对比
TCP:打电话

  • 三次握手四次挥手
  • 连接,稳定
  • 客户端、服务端
  • 传输完成,释放连接,效率低

UDP:发短信

  • 不连接、不稳定
  • 客户端、服务端:没有明确的界限
  • 不管有没有准备好,都可以发给你…
  • 导弹
  • DDOS:洪水攻击!(饱和攻击)

1.6TCP

客户端

  1. 连接服务器Socket
  2. 发送消息
 Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            //1、创建Socket对象,指明服务器的ip和端口号
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet, 9090);
            //2、获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3、写出数据的操作
            fis = new FileInputStream(new File("01.jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read())!=-1){
                os.write(buffer,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            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();
                }
            }
        }
/*
客户端发送信息给服务端,服务端将数据显示

*/

服务器

  1. 建立服务器端口ServerSocket
  2. 等待用户链接 accept
  3. 接收用户的消息
  ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            //1、创建服务器端的ServerSocket,指明自己的端口号
            ss = new ServerSocket(9090);
            //2、调用accept()表示接受来自于客户端的socket
            socket = ss.accept();
            //3、获取输入流
            is = socket.getInputStream();
            //4、读取输入流中的数据
            fos = new FileOutputStream(new File("dog.jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read())!=-1){
                fos.write(buffer,0,len);
            }
            System.out.println("文件已经写出,请及时查收");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fos!=null){
                try {
                    //5、关闭资源
                    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(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    /*
    运行结果:文件已经写出,请及时查收
    */

1.6.1文件上传

/*
客户端发送文件给服务端,服务端保存到本地
*/

客户端

 Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            //1、创建Socket对象,指明服务器的ip和端口号
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet, 9090);
            //2、获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3、写出数据的操作
            fis = new FileInputStream(new File("01.jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read())!=-1){
                os.write(buffer,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            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();
                }
            }
        }

服务端

  ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            //1、创建服务器端的ServerSocket,指明自己的端口号
            ss = new ServerSocket(9090);
            //2、调用accept()表示接受来自于客户端的socket
            socket = ss.accept();
            //3、获取输入流
            is = socket.getInputStream();
            //4、读取输入流中的数据
            fos = new FileOutputStream(new File("dog.jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read())!=-1){
                fos.write(buffer,0,len);
            }
            System.out.println("文件已经写出,请及时查收");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fos!=null){
                try {
                    //5、关闭资源
                    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(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    /*
    运行结果:文件已经写出,请及时查收
    */

1.6.2Tomcat

服务端

  • 自定义 S
  • Tomcat服务器 S

客户端

  • 自定义 C
  • 浏览器 B

1.7UDP

//1、创建数据报套接字并将其绑定到本地主机上的指定端口。
public DatagramSocket(int port)
//2、构造 DatagramPacket,用来接收长度为 length 的数据包
public DatagramPacket(byte buf[], int offset, int length)
//3、从此套接字接收数据报包
public synchronized void receive(DatagramPacket p)
//4、返回数据缓冲区
public synchronized byte[] getData()
//5、返回将要发送或接收到的数据的长度
public synchronized int getLength()

发短信:不用链接,需要知道对方地址!
发送:

      DatagramSocket socket = null;
        try {
            //1、创建发送端
            socket = new DatagramSocket();
            //2、建立数据包
            String str = "你好,我是UDP方法的发送方";
            byte[] data = str.getBytes();
            InetAddress inet = InetAddress.getLocalHost();
            DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9091);
            //3、调用DatagramSocket的发送方法
            socket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //4、关闭socket
            if(socket!=null){
                socket.close();
            }
        }

接收:

       DatagramSocket socket = null;
        try {
            //1、创建接受端,指明端口
            socket = new DatagramSocket(9091);
            //2、建立数据包
            byte[] buffer = new byte[100];
            DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
            //3、调用DatagramSocket的接收方法
            socket.receive(packet);

            System.out.println(new String(packet.getData(),0,packet.getLength()));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //4、关闭socket
            if(socket!=null){
                socket.close();
            }
        }
        /*
        运行结果:你好,我是UDP方法的发送方
        */

多线程在线发消息
发送方

import java.io.BufferedReader;
import java.io.InputstreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net. InetSocketAddress;
public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private int fromPort;
    private string toIP;
    private int toPort;

    public TalkSend(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 (Exception e) {
            e.printstackTrace();
        }
    }
    public void run(){
        while (true){
            try{
                String data = reader.readLine();byte[datas = data.getBytes();
                 DatagramPacket packet = new DatagramPacket(datas, 0,datas.length,new InetsocketAddress(this.to1p ,this.toPort));
                 socket.send(packet);
                if (data.equals ( "bye"")){
                    break;
        }catch (Exception e) {
                e.printstackTrace();

            }
        }
        socket.close();
    }
}



接收方

```java
 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) {
            try {
                //准备接收包裹
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);
                //阻塞式接收包裹
                //断开连接 bye
                byte[] data = packet.getData();
                string receiveData = new string(data,0,data.length);
                system.out.print1n(msgFrom + ": " + receiveData);
                if (receiveData.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                e.printstackTrace();
            }
        }
        socket.close();


    }

其他交互方

public class TalkTeacher {
        public static void main(string[]args) "{
                new Thread(new TalkSend( fromPort: 5555,tolP:"localhost" , toPort: 8888)) .start();
                new Thread( new TalkReceive( port: 9999,msgFrom:"学生")).start();
/*
老师,学生也一样
*/

1.8URL

常用方法:

  • 1、获取该URL的协议名
    public String getProtocol()
  • 2、获取该URL的主机名
    public String getHost()
  • 3、获取该URL的端口号
    public String getPort()
  • 4、获取该URL的文件路径
    public String getPath()
  • 5、获取该URL的文件名
    public String getFile()
  • 6、获取该URL的查询名
    public String getQuery()

下载url文件

import java.io.FileCutputstream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net. uRL;
public class UrlDown {
        public static void main(String[ ] args ) throws Exception{
            //卜裁地址
        URL url = new URL( spec:"http://localhost:8080/qinjiang/SecurityFile.txt" );
        //2.连接到这个资源HTTp
        HttpURLConnection urlConnection = (HttpURLConnection) ur1.openConnection();
        Inputstream inputstream = ur1connection.getInputstream() ;
        Fileoutputstream fos = new Fileoutputstream("SecurityFile.txt" );
        byte[] buffer = new byte[1024];
        int ien;
        while ((len=inputStreanm.read( buffer))!=-1){
            fos.write( buffer,0,len); //写出这个数期
        }
        fos.close();
        input5tream.clcse(;
        ur1connection.disconnect();//断开链接
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值