ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java网络编程基础

2021-11-06 13:31:34  阅读:130  来源: 互联网

标签:java socket 编程 网络 Java new close import net


文章目录

1 概述

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

2 网络通信要素

通信双方地址

  • ip
  • 端口号

通讯协议

  • 应用层: HTTP
  • 表示层
  • 会话层
  • 传输层:TCP UDP
  • 网络层: IP
  • 数据链路层
  • 物理层

思考

  • 如何准确的定位到网络的一台或者多台主机? 通过IP找到不同的主机
  • 找到主机之后如何进行通信? 通过不同的端口区分不同的程序

3 IP地址

对应的java类:InetAddress

  • 唯一定位一台网络上的计算机
  • 127.0.0.1 :本机localhost

ip地址分类

  • IPV4/ IPV6

    • IPV4 32位 , 4个字节组成,一共42个亿,30亿在北美,亚洲4亿,2011年用尽
    • IPV6 128位, 8个无符号整数
  • 公网(互联网)/私网(局域网)

    • 公网
    • 私网
    • ABCD类

域名:为了记忆方便,网站一般都通过域名绑定IP地址

域名 ----》 DNS服务器解析出IP ----》 通过IP进行访问

4 端口

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

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

  • 被规定0-65535

  • TCP UDP: 65535*2 同一协议端口不能相同

  • 公共端口 0 ~1023

  • HTTP:80

  • HTTPS:443

  • FTP:21

  • Telent:23

  • 程序注册端口:1024~49151

  • 动态~私有 49152 - 65535

查看端口 netstat -ano #查看所有的端口
windows:netstat -ano | findstr “5900”
linux: netstat -ano | grep"5900"

5 TCP

客户端

  1. 链接服务器socket
  2. 发送消息
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

// tcp客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            // 1 要知道服务器地址,端口号
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            // 2 创建一个socket链接
            socket = new Socket(serverIP, port);
            // 3 发送信息 IO流
            os = socket.getOutputStream();

            os.write("hello server".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. 建立服务的端口
  2. 等待用户的链接accept
  3. 接收用户的消息
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

// tcp服务器
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            // 1 我得有一个地址
            serverSocket = new ServerSocket(9999);

            while(true){
                // 2 等待客户端链接过来
                socket = serverSocket.accept();
                // 3 读取客户端得消息
                is = socket.getInputStream();
                // 4 管道流
                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();
                }
            }
        }
    }
}

6 文件上传

客户端

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

public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception {
        // 1 创建一个socket链接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        // 2 创建一个输出流
        OutputStream os = socket.getOutputStream();
        // 3 读取文件
        FileInputStream fis = new FileInputStream(new File("A.jpg"));
        // 4 写出文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.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(buffer2))!=-1){
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());
        // 5 关闭资源
        baos.close();
        inputStream.close();
        fis.close();
        os.close();
        socket.close();
    }
}

服务器

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception {
        // 1 创建服务
        ServerSocket serverSocket = new ServerSocket(9000);
        // 2 监听客户端链接,
        Socket socket = serverSocket.accept(); // 阻塞监听,会一直等待客户端链接
        // 3 获取输入流
        InputStream is = socket.getInputStream();
        // 4 文件输出
        FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
        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(StandardCharsets.UTF_8));

        // 5 关闭资源
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

7 UDP

7.1 基础应用

UDP没有客户端、服务器的概念,只有发送端和接收端

发送端代码

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        // 1 建立一个socket
        DatagramSocket socket = new DatagramSocket();
        // 2 需要一个包
        String msg = "hello server";
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, InetAddress.getByName("localhost"), 9090);
        // 3 发送包
        socket.send(packet);
        // 4 关闭资源
        socket.close();
    }
}

接收端代码

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

public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        // 开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        // 接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet); // 阻塞接收
        // 打印接收参数
        System.out.println(packet.getAddress().getHostAddress() + "--->" + new String(packet.getData(), 0, packet.getLength()));
        // 关闭链接
        socket.close();
    }
}

7.2 UDP聊天室

循环发送端

在这里插入图片描述

循环接收端

在这里插入图片描述

标签:java,socket,编程,网络,Java,new,close,import,net
来源: https://blog.csdn.net/kobe_okok/article/details/121054498

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有