📅  最后修改于: 2023-12-03 14:43:04.708000             🧑  作者: Mango
Java是一门功能强大的编程语言,它提供了丰富的网络编程功能。在本文中,我们将介绍一些基本的Java网络编程示例,并通过示例代码来说明。
使用Java可以轻松地建立TCP连接。以下是一个简单的示例代码:
import java.io.*;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
try {
// 创建Socket对象,指定连接的主机和端口号
Socket socket = new Socket("localhost", 8080);
// 获取输入输出流
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
// 发送数据
outputStream.write("Hello, Server!".getBytes());
// 接收数据
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
String response = new String(buffer, 0, bytesRead);
System.out.println("Server response: " + response);
// 关闭连接
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Java可以轻松地创建一个简单的HTTP服务器。以下是一个示例代码:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class HTTPServer {
public static void main(String[] args) {
try {
// 创建ServerSocket对象,指定监听的端口号
ServerSocket serverSocket = new ServerSocket(8080);
// 监听客户端请求
while (true) {
Socket clientSocket = serverSocket.accept();
// 获取输入输出流
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
// 接收客户端请求
String request = reader.readLine();
System.out.println("Received request: " + request);
// 发送HTTP响应
writer.println("HTTP/1.1 200 OK");
writer.println("Content-Type: text/html");
writer.println();
writer.println("<html><body><h1>Hello, World!</h1></body></html>");
writer.flush();
// 关闭连接
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java还支持使用UDP协议发送和接收数据。以下是一个简单的示例代码:
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
try {
// 创建DatagramSocket对象
DatagramSocket socket = new DatagramSocket();
// 指定服务器地址和端口号
InetAddress serverAddress = InetAddress.getByName("localhost");
int serverPort = 8080;
// 发送数据
String message = "Hello, Server!";
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, serverAddress, serverPort);
socket.send(packet);
// 接收数据
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Server response: " + response);
// 关闭连接
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上是几个基本的Java网络编程示例。使用Java网络编程,您可以轻松地创建各种网络应用程序和服务端程序。请根据您的具体需求选择适合的示例代码。