Java基础-网络编程

1. 网络通讯要素概述

  • IP和端口号
  • OSI参考模型(模型过于理想化,未)和TCP/IP参考模型

通信协议

2. 通信要素1:IP和端口号

  • IP:唯一的标识Internet上的计算机,在Java中InetAddress类表示
  • 本地回环地址(hostAddress):127.0.0.1 主机名(hostName):localhost
  • 端口号标识正在计算机运行的进程,被规定一个16位的整数0-65535
  • 端口号与IP地址的组合得出一个网络套接字Socket
public class InetAddressTest {
    public static void main(String[] args) throws UnknownHostException {
        InetAddress inet1 = InetAddress.getByName("127.0.0.1");
        System.out.println(InetAddress.getLocalHost());
        InetAddress inet2 = InetAddress.getByName("www.baidu.com");
        System.out.println(inet1);
        System.out.println(inet2);
    }
}

3. 通信要素2:网络协议

  • 传输层协议中有两个重要的协议:传输控制协议TCP(Transmission Control Protocol)、用户数据报协议UDP(User Datagram Protocol)
  • IP(Internet Protocol)协议是网络层的主要协议,支持网间互联的数据通信
    TCP
    TCP

TCP:使用TCP协议前,先建立TCP连接,形成传输数据通道
传输前,采用“三次握手”,点对点通信,是可靠的
在连接中可进行大数据量的传输
传输完毕,需释放已建立的连接,效率低
UDP:将数据、源、目的封装成数据包,不需要建立连接
每个数据报的大小限制在64K内
发送不管对方是否准备好,接收方收到也不确认,是不可靠的
可以广播发送,发送数据结束时,无法释放资源,开销小,速度快

4. TCP网络编程

//实现TCP的网络编程
//1.客户端发送信息给服务端,服务端将数据显示在控制台
public class TCPTest1 {
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet, 8899);
            //2.获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3.写出数据的操作
            os.write("你好,我是客户端".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() throws IOException {

        //1.创建服务器的Socket,指明自己的端口号
        ServerSocket ss = new ServerSocket(8899);
        //2.调用方法,表示接受来自于客户端的socket
        Socket socket = ss.accept();
        //3.获取输入流
        InputStream is = socket.getInputStream();

        //4.读取输入流的数据
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[5];
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        System.out.println(baos.toString());
        System.out.println(socket.getInetAddress().getHostAddress());
        //关闭资源
        baos.close();
        is.close();
        socket.close();
        ss.close();
    }
}
//实现TCP网络编程,客户端发送文件到服务端,服务端将文件保存本地,并发送“成功”给客户端
public class TCPTest2 {
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream("ex.png");

        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        //关闭数据的输出
        socket.shutdownOutput();
        //接受服务器端给客户端反馈
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferr = new byte[20];
        int len1;
        while ((len1 = is.read(bufferr)) != -1) {
            baos.write(bufferr, 0, len1);
        }
        System.out.println(baos.toString());

        baos.close();
        is.close();
        fis.close();
        os.close();
        socket.close();
    }

    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(9999);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("server2.png");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }


        OutputStream os = socket.getOutputStream();
        os.write("服务端接受成功".getBytes());

        os.close();
        fos.close();
        fos.close();
        is.close();
        ss.close();
    }
}

5. UDP网络编程

  • 类DatagramSocket和DatagramPacket实现了基于UDP协议网络程序
//UDP协议的网络编程
public class UDPTest {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String str = "我是UDP";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getByName("127.0.0.1");
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 9000);
        socket.send(packet);
        socket.close();
    }

    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(9000);
        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);

        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        socket.close();
    }
}

6. URL编程

  • URL(Uniform Resource Locator)统一资源定位器,表示网络上某一个资源的地址
  • URL基本结构由5部分组成:<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表 参数列表格式:参数名=参数值&参数名=参数值
//URL网络编程
public class URLTest1 {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://www.baidu.com:8000/exp/doc.txt?us=tom");
        System.out.println(url.getProtocol());
        System.out.println(url.getHost());
        System.out.println(url.getPath());
        System.out.println(url.getFile());
        System.out.println(url.getQuery());
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        InputStream is = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("doc.txt");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        System.out.println("下载完成");
        is.close();
        fos.close();
        urlConnection.disconnect();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值