【Java复习巩固 Day9】网络编程

所谓计算机网络,就是把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息,共享硬件、软件、数据信息等资源

OSI参考模型
【Java复习巩固 Day9】网络编程_第1张图片
【Java复习巩固 Day9】网络编程_第2张图片

InetAddress

package day9;

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

public class INetAddressTest {
    public static void main(String[] args) {
        try {
            // 查询本机地址
            InetAddress inetAddress = InetAddress.getByName("localhost");
            System.out.println(inetAddress);
            // 查询网站IP地址
            InetAddress inetAddress1 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress1);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

localhost/127.0.0.1
www.baidu.com/180.101.49.11

Process finished with exit code 0

InetAddress类本身并没有提供太多功能,它代表一个IP地址对象,是网络通信的基础

URL

package day9;

import java.net.URL;

public class URLDemo1 {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=java&fenlei=256&rsv_pq=e5d7c5d100028b57&rsv_t=0146pPKjeDrb%2FOwTUi6girx9sjwBUdZqouTbB8vhFZAlY3xzxDgierUe7iQ&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=8&rsv_sug1=8&rsv_sug7=101&rsv_sug2=0&rsv_btype=i&inputT=2848&rsv_sug4=2848");
        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());
    }
}

package day9;

import java.net.URLDecoder;
import java.net.URLEncoder;

// 测试URLDecoder和URLEncoder
public class URLDecoderTest {
    public static void main(String[] args) throws Exception {
        String urlString = URLEncoder.encode("中文", "UTF-8");
        System.out.println(urlString);
        String keyWord = URLDecoder.decode("%E4%B8%AD%E6%96%87", "UTF-8");
        System.out.println(keyWord);
    }
}


%E4%B8%AD%E6%96%87
中文

TCP

传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议
TCP旨在适应支持多网络应用的分层协议层次结构。 连接到不同但互连的计算机通信网络的主计算机中的成对进程之间依靠TCP提供可靠的通信服务。TCP假设它可以从较低级别的协议获得简单的,可能不可靠的数据报服务。 原则上,TCP应该能够在从硬线连接到分组交换或电路交换网络的各种通信系统之上操作。
TCP协议被称作一种端对端协议

【Java复习巩固 Day9】网络编程_第3张图片
用TCP实现简单的B/S通信

package day9;

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


// 客户端
public class TCPClientDemo1 {
    public static void main(String[] args) throws Exception {
        InetAddress serverIP = InetAddress.getByName("127.0.0.1");
        int port = 9999;
        Socket socket = new Socket(serverIP, port);
        // 发送消息
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("Hello World!".getBytes());
        outputStream.close();
        socket.close();
    }
}

package day9;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

// 服务端
public class TCPServerDemo1 {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(9999);
        Socket socket = serverSocket.accept();
        // 读取客户端的消息
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = inputStream.read(bytes)) != -1) {
            byteArrayOutputStream.write(bytes, 0, len);
        }
        System.out.println(byteArrayOutputStream.toString());
        byteArrayOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}

UDP

nternet 协议集支持一个无连接的传输协议,该协议称为用户数据报协议(UDP,User Datagram Protocol)。UDP 为应用程序提供了一种无需建立连接就可以发送封装的 IP 数据包的方法
Internet 的传输层有两个主要协议,互为补充。无连接的是 UDP,它除了给应用程序发送数据包功能并允许它们在所需的层次上架构自己的协议之外,几乎没有做什么特别的事情。

【Java复习巩固 Day9】网络编程_第4张图片
基于UDP的简单聊天室

发送端代码如下:

package day9;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;

public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    Scanner scanner = null;
    private int toPort;
    private String toIP;
    private int fromPort;

    public int getToPort() {
        return toPort;
    }

    public void setToPort(int toPort) {
        this.toPort = toPort;
    }

    public String getToIP() {
        return toIP;
    }

    public void setToIP(String toIP) {
        this.toIP = toIP;
    }

    public int getFromPort() {
        return fromPort;
    }

    public void setFromPort(int fromPort) {
        this.fromPort = fromPort;
    }

    public TalkSend(int toPort, String toIP, int fromPort) {
        this.toPort = toPort;
        this.toIP = toIP;
        this.fromPort = fromPort;
        scanner = new Scanner(System.in);
        try {
            socket = new DatagramSocket(fromPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            String data = scanner.nextLine();
            byte[] bytes = data.getBytes();
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress(toIP, toPort));
            try {
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (data.equals("exit")) {
                break;
            }
        }
        socket.close();
    }
}

接收端代码如下:

package day9;

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();
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        while (true) {
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            try {
                socket.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] bytes = packet.getData();
            String receiveData = new String(bytes, 0, bytes.length);
            System.out.println(msgFrom + ": " + receiveData);
            if (receiveData.equals("exit")) {
                break;
            }
        }
        socket.close();
    }
}


【Java复习巩固 Day9】网络编程_第5张图片

你可能感兴趣的:(Java,java,socket)