Java 网络编程学习笔记

什么是网络编程?

网络编程是指利用计算机网络技术进行软件开发的过程。通过网络编程,我们可以编写出能与其他计算机上的程序进行通信的应用程序。

在Java中,我们可以使用Socket类和ServerSocket类来实现基本的网络编程功能。

Socket类

Socket类表示通信的端点,可用于客户端和服务器端的通信。常用的Socket类方法有:

  • getInputStream():获取输入流
  • getOutputStream():获取输出流
  • connect(SocketAddress endpoint):连接到指定的地址
  • bind(SocketAddress bindpoint):将Socket绑定到特定IP地址和端口号

以下是一个简单的Java Socket客户端示例代码:

javaCopy Code
import java.io.*; import java.net.*; public class MyClient { public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 12345); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdin.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); if (userInput.equals("bye")) { break; } } out.close(); in.close(); stdin.close(); socket.close(); } }

该代码创建了一个Socket连接到本地主机的12345端口,并通过Socket的输入输出流与服务器进行通信。

ServerSocket类

ServerSocket类用于创建服务器端Socket,等待客户端的连接。常用的ServerSocket类方法有:

  • accept():等待客户端连接
  • bind(SocketAddress endpoint):将ServerSocket绑定到特定IP地址和端口号

以下是一个简单的Java Socket服务器端示例代码:

javaCopy Code
import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(12345); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.equals("bye")) { break; } out.println(inputLine); } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } }

该代码创建了一个ServerSocket等待客户端连接,并通过Socket的输入输出流与客户端进行通信。

实例:基于Socket的简单聊天室

下面是一个基于Socket的简单聊天室示例代码:

javaCopy Code
import java.io.*; import java.net.*; import java.util.*; public class ChatRoomServer { private static final int PORT = 12345; private static List<Socket> clients = new ArrayList<Socket>(); public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(PORT); System.out.println("聊天室服务器已启动,正在监听端口 " + PORT + "..."); try { while (true) { Socket clientSocket = serverSocket.accept(); System.out.println("客户端 " + clientSocket.getRemoteSocketAddress() + " 已连接。"); clients.add(clientSocket); new Thread(new ClientHandler(clientSocket)).start(); } } finally { serverSocket.close(); } } private static class ClientHandler implements Runnable { private Socket clientSocket; private BufferedReader in; private PrintWriter out; public ClientHandler(Socket socket) { this.clientSocket = socket; } public void run() { try { in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); out = new PrintWriter(clientSocket.getOutputStream(), true); String name = in.readLine(); out.println("欢迎加入聊天室," + name + "!"); while (true) { String input = in.readLine(); if (input == null) { return; } for (Socket client : clients) { PrintWriter writer = new PrintWriter(client.getOutputStream(), true); writer.println(name + ": " + input); } } } catch (IOException e) { System.out.println(e); } finally { try { clientSocket.close(); } catch (IOException e) { } } } } }

该代码创建了一个基于Socket的简单聊天室服务器,允许多个客户端连接,客户端可以发送消息到聊天室中,其他客户端可以接收消息并进行回复。