Java网络编程基础知识学习笔记

B站视频指路:尚硅谷Java入门视频教程(在线答疑+Java面试真题)_哔哩哔哩_bilibili

写在前面:马上秋招,打算从0开始再学一遍Java,开个知识点记录贴,就当做课堂笔记吧.

网络编程概述:
        ·Java是Internet上的语言 它从语言级上提供了对网络应用程序的支持 程序员很容易开发常见的网络应用程序
        ·Java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在Java的本机安装系统里,由JVM进行控制.并且Java实现了一个跨平台的网络库,程序员面对的是一个统一的网络编程环境.

网络基础
·计算机网络:      

·网络编程的目的:
        直接或间接地通过网络协议与其它计算机实现数据交换 进行通讯
·网络编程中有两个主要的问题
        ·如何准确地定位网络上一台或多台主机 定位主机上的特定的应用
        ·找到主机后如何可靠高效的进行数据传输


如何实现网络中的主机互相通信
        ·通信双方地址
                IP、端口号
        ·一定的规则(即:网络通信协议 有两套参考模型)
                OSI参考模型:过于理想化 未能在Internet上进行广泛推广
                TCP/IP参考模型(也称TCP/IP协议):事实上的国际标准
                        应用层、传输层、网络层、物理和数据链路层

网络编程中的两个要素
       ①对应问题1:IP号和端口号
       ②对应问题2:网路通信协议

 

网络通信协议

OSI参考模型TCP/IP参考模型TCP/IP参考模型各层对应协议
应用层应用层HTTP、FTP、Telnet、DNS...
表示层
会话层
传输层传输层TCP、UDP...
网络层网络层IP、ICMP、ARP...
数据链路层物理+数据链路层Link
物理层

数据传输的例子

  通信要素一:IP和端口号
        端口号与IP地址的组合得出一个网络套接字:Socket

        IP地址:

        1.IP:唯一的标识Internet上的计算机(通信实体)
        2.在Java中使用InetAddress类代表IP
        3.IP分类: IPv4、IPv6; 万维网和局域网
        4.域名:www.baidu.com ...
        5.本地回路地址:127.0.0.1 对应着:localhost
        6.如何实例化InetAddress:①getByName(String host)、getLocalHost()
                常用方法:①getHostName()②getHostAddress()

package ipyoyoyo;

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

public class Inet {
    public static void main(String[] args) {
        try {
            InetAddress byName = InetAddress.getByName("192.168.0.12");
            System.out.println(byName);
            InetAddress byName2 = InetAddress.getByName("www.atguigu.com");
            System.out.println(byName2);
            InetAddress byName3 = InetAddress.getByName("127.0.0.1");
            System.out.println(byName3);
            //获取本机ip
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);

            //getHostName
            String hostName = byName2.getHostName();
            System.out.println(hostName);
            //getHostAddress
            String hostAddress = byName2.getHostAddress();
            System.out.println(hostAddress);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

        端口号:
        ·不同进程有不同的端口号
        ·范围:被规定为一个16位整数0~65535

 访问流程:

   通信要素二:网络协议

 传输层协议中有两个非常重要的协议:
        ①传输控制协议TCP(Transmission Control Protocol)
        ②用户数据报协议UDP(User Datagram Protocol)
                ·TCP/IP 以其两个主要协议:传输控制协议TCP和网络互连协议IP而得名,实际上是一组协议,包括多个具有不同功能且互为关联的协议
                ·IP(Internet Protocol)协议是网络层的主要协议,支持网间互连的数据通信
                ·TCP/IP协议模型从更实用的角度出发,形成了高效的四层体系结构,即物理链路层、IP层、传输层和应用层

TCP和UDP
·TCP协议
        ①使用TCP协议前,须先建立TCP连接,形成传输数据通道
        ②传输前采用"三次握手"方式,点对点通信,是可靠的
        ③TCP协议进行通信的两个应用进程:客户端、服务器
        ④在连接中进行大数据量的传输
        ⑤传输完毕,需释放已建立的链接,效率低
·UDP协议
        ①将数据、源、目的封装成数据包,不需要建立连接
        ②每个数据报的大小限制在64K内
        ③发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
        ④可以广播发送
        ⑤发送数据结束时无需释放资源,开销小,速度快

 实现TCP的网络编程:
例题:


   1.客户端:
        ①创建Socket对象 指明服务器端的ip和端口号
        ②获取一个输出流 用于输出数据
        ③写出数据的操作
        ④资源的关闭
       服务端:
        ①创建服务器端的SercerSocket,指明自己的端口号
        ②调用accept()表示接收来自于客服端的socket
        ③获取输入流
        ④读取输入流中的数据
        ⑤资源的关闭

package ipyoyoyo;

import org.junit.Test;

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


public class TCPTst {
    @Test
    //客户端
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inetAddress,2211);

            os = socket.getOutputStream();
            os.write("hello".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os!=null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    //服务端 属于被动的 它一启动 就等客户端去链接了 所以先启动服务端
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            serverSocket = new ServerSocket(2211);
            accept = serverSocket.accept();
            inputStream = accept.getInputStream();

            //不建议这么写 可能会乱码 因为字节流 汉字可能乱码
//        int len;
//        byte[] buff = new byte[20];
//        while ((len=inputStream.read(buff))!=-1){
//            String s = new String(buff,0,len);
//            System.out.println(s);
//        }
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[5];
            int len;
            while ((len=inputStream.read(buff))!=-1){
                byteArrayOutputStream.write(buff,0,len);
            }
            System.out.println(byteArrayOutputStream);
            System.out.println("收到了从:"+accept.getInetAddress().getHostAddress()+"发来的数据!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(accept!=null)
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(byteArrayOutputStream!=null)
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(inputStream!=null)
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(serverSocket!=null)
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }
}


2.

package ipyoyoyo;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class lizier {
    @Test
    //客户端
    public void client() {
        FileInputStream fileInputStream = null;
        Socket socket = null;
        OutputStream os = null;
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"),2210);
            os = socket.getOutputStream();
            fileInputStream = new FileInputStream("报名照片.jpg");
            int len;
            byte[] buf = new byte[1024];
            while((len=fileInputStream.read(buf))!=-1){
                os.write(buf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os!=null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fileInputStream!=null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    //服务端 属于被动的 它一启动 就等客户端去链接了 所以先启动服务端
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            serverSocket = new ServerSocket(2210);
            accept = serverSocket.accept();
            inputStream = accept.getInputStream();
            fileOutputStream = new FileOutputStream("zhangkekeke.jpg");
            //不建议这么写 可能会乱码 因为字节流 汉字可能乱码
//        int len;
//        byte[] buff = new byte[20];
//        while ((len=inputStream.read(buff))!=-1){
//            String s = new String(buff,0,len);
//            System.out.println(s);
//        }

            byte[] buff = new byte[5];
            int len;
            while ((len=inputStream.read(buff))!=-1){
                fileOutputStream.write(buff,0,len);
            }
            System.out.println("收到了从:"+accept.getInetAddress().getHostAddress()+"发来的数据!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(accept!=null)
                    accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fileOutputStream!=null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(inputStream!=null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(serverSocket!=null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }
}

 3.

package ipyoyoyo;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class sdafsdf {
    @Test
    //客户端
    public void client() {
        FileInputStream fileInputStream = null;
        Socket socket = null;
        OutputStream os = null;
        InputStream inputStream = null;
        ByteArrayOutputStream bs = null;
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"),2210);
            os = socket.getOutputStream();
            fileInputStream = new FileInputStream("报名照片.jpg");
            int len;
            byte[] buf = new byte[1024];
            while((len=fileInputStream.read(buf))!=-1){
                os.write(buf,0,len);
            }
            //关闭数据的输出 没这句话的话 服务端会一直在等 客户端传输
            socket.shutdownOutput();
            inputStream = socket.getInputStream();
            bs = new ByteArrayOutputStream();
            byte[]buff = new byte[20];
            int len2;
            while((len2=inputStream.read(buff))!=-1){
                bs.write(buff,0,len2);
            }
            System.out.println(bs.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os!=null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fileInputStream!=null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(bs!=null)
                    bs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(inputStream!=null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    @Test
    //服务端 属于被动的 它一启动 就等客户端去链接了 所以先启动服务端
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            serverSocket = new ServerSocket(2210);
            accept = serverSocket.accept();
            inputStream = accept.getInputStream();
            fileOutputStream = new FileOutputStream("z.jpg");
            //不建议这么写 可能会乱码 因为字节流 汉字可能乱码
//        int len;
//        byte[] buff = new byte[20];
//        while ((len=inputStream.read(buff))!=-1){
//            String s = new String(buff,0,len);
//            System.out.println(s);
//        }

            byte[] buff = new byte[5];
            int len;
            while ((len=inputStream.read(buff))!=-1){
                fileOutputStream.write(buff,0,len);
            }
            System.out.println("收到了从:"+accept.getInetAddress().getHostAddress()+"发来的数据!");
            //服务器端基于客户端反馈
            outputStream = accept.getOutputStream();
            outputStream.write("shoudaola!".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(accept!=null)
                    accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fileOutputStream!=null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(inputStream!=null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(serverSocket!=null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(outputStream!=null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class jkas {
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("localhost"),1996);
        InputStream inputStream = socket.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream("Z32532523.jpg");


        int len;
        byte[] buf = new byte[1024];
        while((len=inputStream.read(buf))!=-1){
            fileOutputStream.write(buf,0,len);
        }
        fileOutputStream.close();
        socket.close();
        inputStream.close();
        fileOutputStream.close();

    }
    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(1996);
        Socket accept = serverSocket.accept();
        OutputStream os = accept.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream("zhangkekeke.jpg");

        int len;
        byte[] buf = new byte[1024];
        while((len=fileInputStream.read(buf))!=-1){
            os.write(buf,0,len);
        }
        serverSocket.close();
        accept.close();

        fileInputStream.close();
    }
}

2.注意shoutdownOutput位置

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Locale;

public class gsdwe {
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("localhost"),2012);
        FileInputStream fileInputStream = new FileInputStream("hello.txt");
        OutputStream os = socket.getOutputStream();
        ByteArrayOutputStream bs = new ByteArrayOutputStream();

        InputStream inss = socket.getInputStream();

        System.out.println(bs.toString());
        int len;
        byte[] c = new byte[5];
        while ((len=fileInputStream.read(c))!=-1){
            os.write(c,0,len);
        }
        socket.shutdownOutput();
        int l;
        byte []buf = new byte[5];
        while((l=inss.read(buf))!=-1){
            bs.write(buf,0,l);
        }
        System.out.println(bs.toString());
        bs.close();
        os.close();
        inss.close();
        socket.close();
        fileInputStream.close();
    }
    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(2012);
        Socket accept = serverSocket.accept();
        InputStream ins = accept.getInputStream();
        OutputStream haa = accept.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[]cha = new byte[5];
        int len;
        while((len=ins.read(cha))!=-1){
            byteArrayOutputStream.write(cha,0,len);
        }
        System.out.println(byteArrayOutputStream);
        haa.write(byteArrayOutputStream.toString().toUpperCase().getBytes());
        byteArrayOutputStream.close();
        ins.close();
        serverSocket.close();
        accept.close();
    }
}

客户端-服务端
        ·客户端:
                自定义
                浏览器
        ·服务端:
                自定义
                Tomcat服务器


UDP网络编程
        ·类DatagramSocket和DatagramPacket实现了基于UDP协议网络.
        ·UDP数据报通过数据报套接字DatagramSocket发送和接受,系统不保证UDP数据报一定
能够安全的送达到目的地,也不确定什么时候可以抵达
        ·DatagramPacket对象封装了UDP数据报,在数据报中包含了发送端IP地址和端口号以及
接收端的IP地址和端口号
        ·UDP协议中每个数据报都给出了完整的地址信息,因此无需建立发送方和接收方的链接.
如同发快递包裹一样
例:(看看就行)

package UDPTest;

import org.junit.Test;

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

public class UdpSnC {
    @Test
    //发送端
    public void send() throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket();
        String s = "UDP ZHANGKE";
        byte [] data = s.getBytes();
        InetAddress localHost = InetAddress.getLocalHost();
        DatagramPacket datagramPacket = new DatagramPacket(data,0,data.length,localHost,2021);
        datagramSocket.send(datagramPacket);
        datagramSocket.close();
    }
    @Test
    //接收端
    public void receive() throws IOException{
        DatagramSocket socket = new DatagramSocket(2021);
        byte [] k = new byte[100];
        DatagramPacket packet = new DatagramPacket(k,0,k.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        socket.close();
    }
}

URL编程
        ·URL(Uniform Resource Locator):统一资源定位符,它表示Internet上某一资源的地址
        ·它是一种具体的URL,即URL可以用来标识一个资源,而且还指明了如何locate这个资源
        ·通过URL我们可以访问Internet上的各种网络资源,比如最常见的www、ftp、站点.浏览器
通过解析给定的URL可以在网络上查找相应的文件或其他资源
        ·URL的基本结构由5部分组成
                <传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
                eg:


                #片段名:即锚点 例如看小说 直接定位到章节
                参数格式列表:参数名=参数值&参数名=参数值...

import java.net.MalformedURLException;
import java.net.URL;

public class URLTest {
    public static void main(String[] args)  {
        try {
            URL url = new URL("http://localhost:8080/examples/z.jpg?username=zk");
            System.out.println(url.getProtocol());
            System.out.println(url.getHost());
            System.out.println(url.getPort());
            System.out.println(url.getPath());
            System.out.println(url.getFile());
            System.out.println(url.getQuery());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

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

public class URLTest {
    public static void main(String[] args)  {

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            URL url = new URL("http://localhost:8080/examples/z.jpg");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            inputStream = urlConnection.getInputStream();
            fileOutputStream = new FileOutputStream("haasdfsdf.jpg");
            byte []buff = new byte[1024];
            int len;
            while((len=inputStream.read(buff))!=-1){
                fileOutputStream.write(buff,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileOutputStream!=null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(inputStream!=null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(urlConnection!=null)
                urlConnection.disconnect();
        }



    }
}

 

 

练习:
1.一个IP对应着哪个类的一个对象?实例化这个类的两种方式是?两个常用的方法是?
        ①InetAddress         
        ②InetAddress .getByName(String host);
            InetAddress .getLocalHost();//获取本地IP对应的InetAddress对象
        ③getHostName()//域名
            getHostAddress()//IP地址

2.传输层的TCP协议和UDP协议的主要区别是?
        TCP:可靠的数据传输(三次握手);进行大数据量的传输;效率低
        UDP:不可靠的数据传输;以数据报的形式进行传输,数据报限定为64k;效率高

3.什么是URL,写一个URL?
        URL:统一资源定位符
        URL url = new URL("httt://128.2.10.0:8080/examples/hello.txt");


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值