了解Java网络编程基础
Java网络编程是Java编程语言的一个重要组成部分,它允许Java程序与网络进行交互。在Java中,网络编程主要依赖于java.net包中的类和接口。以下是一些基本的网络编程概念:
1. 网络协议
网络协议是计算机之间通信的规则和约定。在Java网络编程中,最常用的协议是TCP/IP。TCP(传输控制协议)是一种面向连接的、可靠的协议,而UDP(用户数据报协议)则是一种无连接的、不可靠的协议。
2. IP地址和端口号
IP地址是网络上每台设备的唯一标识。端口号用于区分同一台设备上运行的不同服务。例如,HTTP服务的默认端口号是80。
3. Socket
Socket是网络通信的基本抽象,它代表了客户端和服务器之间的连接。在Java中,Socket类用于创建客户端和服务器之间的连接。
创建简单的TCP服务器
下面是一个简单的Java TCP服务器示例,它监听本地的9999端口,等待客户端的连接请求。
import java.io.*;
import java.net.*;
public class SimpleServer {
public static void main(String[] args) throws IOException {
int port = 9999;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected");
// 处理客户端请求
new Thread(new ClientHandler(clientSocket)).start();
}
}
}
class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
out.println("Echo: " + inputLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
创建简单的TCP客户端
下面是一个简单的Java TCP客户端示例,它连接到服务器并发送一条消息。
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
String host = "localhost";
int port = 9999;
Socket socket = new Socket(host, port);
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("Server response: " + in.readLine());
}
socket.close();
}
}
实战案例详解
在这个案例中,我们将创建一个简单的文件传输程序,允许客户端向服务器发送文件。
服务器端
服务器端将监听客户端的连接请求,并接收文件。
// 省略了前面的导入和类定义
public class FileServer {
public static void main(String[] args) throws IOException {
int port = 9999;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
new Thread(new FileServerHandler(clientSocket)).start();
}
}
}
class FileServerHandler implements Runnable {
private Socket clientSocket;
public FileServerHandler(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
// 读取文件名
DataInputStream dataInput = new DataInputStream(input);
String fileName = dataInput.readUTF();
System.out.println("Received file name: " + fileName);
// 保存文件
FileOutputStream fileOutput = new FileOutputStream(fileName);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
fileOutput.write(buffer, 0, bytesRead);
}
fileOutput.close();
System.out.println("File received: " + fileName);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端
客户端将连接到服务器,并发送一个文件。
// 省略了前面的导入和类定义
public class FileClient {
public static void main(String[] args) throws IOException {
String host = "localhost";
int port = 9999;
String filePath = "example.txt";
Socket socket = new Socket(host, port);
DataOutputStream dataOutput = new DataOutputStream(socket.getOutputStream());
FileInputStream fileInput = new FileInputStream(filePath);
dataOutput.writeUTF(filePath); // 发送文件名
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInput.read(buffer)) != -1) {
dataOutput.write(buffer, 0, bytesRead);
}
fileInput.close();
dataOutput.close();
socket.close();
}
}
总结
通过以上示例,我们可以看到如何使用Java创建简单的TCP服务器和客户端。这些示例展示了如何使用Socket进行网络通信,以及如何发送和接收数据。希望这些示例能够帮助你入门Java网络编程。
