Java中的网络编程:从Socket到NIO

[复制链接]
发表于 2026-2-14 16:42:36 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Java中的网络编程:从Socket到NIO
各人好,我是微赚淘客体系3.0的小编,是个冬天不穿秋裤,天冷也要风度的步调猿!本日我们来探究Java中的网络编程,从底子的Socket编程到更高级的NIO(New Input/Output)编程。
一、Socket编程
Socket是Java网络编程的底子,它提供了毗连两个节点之间通讯的机制。利用Socket,我们可以实现客户端和服务器之间的数据传输。
  1. package cn.juwatech.networking;
  2. import java.io.IOException;
  3. import java.io.OutputStream;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. public class Server {
  7.     public static void main(String[] args) {
  8.         try (ServerSocket serverSocket = new ServerSocket(8080)) {
  9.             System.out.println("Server is listening on port 8080");
  10.             while (true) {
  11.                 Socket socket = serverSocket.accept();
  12.                 System.out.println("New client connected");
  13.                 OutputStream output = socket.getOutputStream();
  14.                 output.write("Hello, client!".getBytes());
  15.                 socket.close();
  16.             }
  17.         } catch (IOException e) {
  18.             e.printStackTrace();
  19.         }
  20.     }
  21. }
复制代码
  1. package cn.juwatech.networking;
  2. import java.io.InputStream;
  3. import java.net.Socket;
  4. public class Client {
  5.     public static void main(String[] args) {
  6.         try (Socket socket = new Socket("localhost", 8080)) {
  7.             InputStream input = socket.getInputStream();
  8.             byte[] data = new byte[1024];
  9.             int bytesRead = input.read(data);
  10.             System.out.println("Received from server: " + new String(data, 0, bytesRead));
  11.         } catch (IOException e) {
  12.             e.printStackTrace();
  13.         }
  14.     }
  15. }
复制代码
二、NIO编程
Java NIO(New Input/Output)提供了面向缓冲区、基于通道的I/O操纵,更适当处置惩罚高并发和大数据量的网络通讯。

  • NIO概述
NIO引入了以下几个核心概念:

  • Channel:代表一个打开到I/O装备(如文件、套接字)的毗连。
  • Buffer:一个用于写入或读取数据的内存块。
  • Selector:用于监听多个通道的变乱(如毗连到达、数据到达等)。
  1. package cn.juwatech.networking;
  2. import java.io.IOException;
  3. import java.net.InetSocketAddress;
  4. import java.nio.ByteBuffer;
  5. import java.nio.channels.SelectionKey;
  6. import java.nio.channels.Selector;
  7. import java.nio.channels.ServerSocketChannel;
  8. import java.nio.channels.SocketChannel;
  9. import java.util.Iterator;
  10. public class NioServer {
  11.     public static void main(String[] args) {
  12.         try (Selector selector = Selector.open();
  13.              ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
  14.             
  15.             serverSocketChannel.bind(new InetSocketAddress(8080));
  16.             serverSocketChannel.configureBlocking(false);
  17.             serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
  18.             
  19.             System.out.println("NIO Server is listening on port 8080");
  20.             while (true) {
  21.                 selector.select();
  22.                 Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
  23.                
  24.                 while (keys.hasNext()) {
  25.                     SelectionKey key = keys.next();
  26.                     keys.remove();
  27.                     
  28.                     if (key.isAcceptable()) {
  29.                         handleAccept(key);
  30.                     } else if (key.isReadable()) {
  31.                         handleRead(key);
  32.                     }
  33.                 }
  34.             }
  35.         } catch (IOException e) {
  36.             e.printStackTrace();
  37.         }
  38.     }
  39.     private static void handleAccept(SelectionKey key) throws IOException {
  40.         ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
  41.         SocketChannel socketChannel = serverSocketChannel.accept();
  42.         socketChannel.configureBlocking(false);
  43.         socketChannel.register(key.selector(), SelectionKey.OP_READ);
  44.         System.out.println("New client connected");
  45.     }
  46.     private static void handleRead(SelectionKey key) throws IOException {
  47.         SocketChannel socketChannel = (SocketChannel) key.channel();
  48.         ByteBuffer buffer = ByteBuffer.allocate(256);
  49.         int bytesRead = socketChannel.read(buffer);
  50.         
  51.         if (bytesRead == -1) {
  52.             socketChannel.close();
  53.         } else {
  54.             System.out.println("Received from client: " + new String(buffer.array()).trim());
  55.             buffer.flip();
  56.             socketChannel.write(ByteBuffer.wrap("Hello, client!".getBytes()));
  57.         }
  58.     }
  59. }
复制代码

  • NIO客户端代码示例
  1. package cn.juwatech.networking;
  2. import java.io.IOException;
  3. import java.net.InetSocketAddress;
  4. import java.nio.ByteBuffer;
  5. import java.nio.channels.SocketChannel;
  6. public class NioClient {
  7.     public static void main(String[] args) {
  8.         try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080))) {
  9.             socketChannel.configureBlocking(false);
  10.             ByteBuffer buffer = ByteBuffer.allocate(256);
  11.             socketChannel.read(buffer);
  12.             System.out.println("Received from server: " + new String(buffer.array()).trim());
  13.         } catch (IOException e) {
  14.             e.printStackTrace();
  15.         }
  16.     }
  17. }
复制代码
三、NIO与传统IO的对比
NIO由于接纳了非壅闭IO和基于通道的模子,可以更好地支持高并发的网络应用,尤其适当大型服务器应用。

  • 编程复杂度
NIO的编程模子比传统IO复杂,必要处置惩罚通道、选择器和缓冲区,但它提供了更高的机动性和性能。
四、最佳实践

  • 选择符合的模子
对于小规模、低并发的应用,可以利用简单的Socket编程。对于高并发、大数据量的应用,发起利用NIO。

  • 资源管理
确保实时关闭通道和选择器,制止资源走漏。利用try-with-resources语句可以简化资源管理。

  • 错误处置惩罚
网络编程中大概会遇到各种非常环境,必要适当的错误处置惩罚机制,确保应用的结实性。
总结
本文先容了Java中的网络编程,从底子的Socket编程到高级的NIO编程。通过这些示例代码,我们可以更好地明确如安在Java中实现高效的网络通讯。
本文著作权归聚娃科技微赚淘客体系开辟者团队,转载请注明出处!
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表