Home > Java > javaTutorial > body text

Network programming practice of Java underlying technology: how to implement Socket communication and NIO

PHPz
Release: 2023-11-08 17:54:59
Original
857 people have browsed it

Network programming practice of Java underlying technology: how to implement Socket communication and NIO

Network programming practice of Java underlying technology: How to implement Socket communication and NIO

1. Introduction

With the rapid development of the Internet, network programming is becoming increasingly important in modern software development. As a language widely used in network programming, Java provides rich underlying technical support. Among them, Socket communication and NIO are two common and important network programming methods in Java. This article will introduce how to use Java to implement Socket communication and NIO, and give specific code examples.

2. Socket communication

Socket communication is a network programming method based on the transport layer protocol. It establishes a communication connection between the client and the server through sockets (Socket). Java provides the Socket and ServerSocket classes in the java.net package for implementing Socket communication.

  1. Client code example
import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) {
        try {
            // 创建Socket对象,并指定服务器的IP地址和端口号
            Socket socket = new Socket("127.0.0.1", 8888);
            
            // 获取输出流,用于向服务器发送数据
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            
            // 向服务器发送数据
            pw.write("Hello, Server!");
            pw.flush();
            
            // 关闭输出流和Socket连接
            pw.close();
            os.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login
  1. Server code example
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        try {
            // 创建ServerSocket对象,并指定监听的端口号
            ServerSocket serverSocket = new ServerSocket(8888);
            
            // 等待客户端连接
            Socket socket = serverSocket.accept();
            
            // 获取输入流,用于接收客户端发送的数据
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            
            // 接收客户端发送的数据
            System.out.println("Received from client: " + br.readLine());
            
            // 关闭输入流、Socket连接和ServerSocket连接
            br.close();
            is.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

3. NIO

NIO (New I/O) is a non-blocking I/O feature in Java that enables highly concurrent network programming by using fewer threads. Java provides Channel, Buffer, Selector and other classes in the java.nio package for implementing NIO.

  1. Client-side code example
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class Client {
    public static void main(String[] args) {
        try {
            // 创建SocketChannel对象,并连接服务器
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 8888));
            
            // 发送数据给服务器
            String message = "Hello, Server!";
            ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
            socketChannel.write(buffer);

            // 关闭SocketChannel连接
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login
  1. Server-side code example
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class Server {
    public static void main(String[] args) {
        try {
            // 创建ServerSocketChannel对象,并绑定监听的端口号
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(8888));
            
            // 设置为非阻塞模式
            serverSocketChannel.configureBlocking(false);

            // 创建Selector对象,并将ServerSocketChannel注册到Selector上
            Selector selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            
            while (true) {
                // 阻塞式等待就绪的事件
                selector.select();
                
                // 获取就绪的事件集合
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectedKeys.iterator();
                
                // 处理就绪事件
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    
                    // 接收客户端连接请求
                    if (key.isAcceptable()) {
                        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = serverChannel.accept();
                        
                        // 设置为非阻塞模式
                        socketChannel.configureBlocking(false);
                        
                        // 注册读事件到Selector上
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    }
                    
                    // 读取客户端发送的数据
                    if (key.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);

                        // 读取数据到缓冲区
                        int bytesRead = socketChannel.read(buffer);
                        if (bytesRead > 0) {
                            buffer.flip();

                            // 提取缓冲区中的数据
                            byte[] data = new byte[bytesRead];
                            buffer.get(data);
                            String message = new String(data);
                            System.out.println("Received from client: " + message);
                        }

                        // 关闭客户端连接
                        socketChannel.close();
                    }

                    // 从处理集合中移除当前就绪的事件
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

IV. Summary

This article Introduces Socket communication and NIO in Java's underlying technology, and gives specific code examples. Through these examples, we can learn how to use Java for network programming, and understand the basic principles and usage of Socket communication and NIO. In actual development, choosing the appropriate network programming method according to specific needs can improve the performance and concurrent processing capabilities of the program. I hope readers can better understand and apply Java's underlying network programming technology through the content of this article.

The above is the detailed content of Network programming practice of Java underlying technology: how to implement Socket communication and NIO. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!