1. Socket 和 ServerSocket:
- Socket: Socket 类表示网络中的一个端点,可以通过它与其他程序进行通信。可以通过 Socket 连接到远程服务器的特定 IP 地址和端口。
import java.io.*;
import java.net.Socket;
public class ClientExample {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
// 发送数据到服务器
out.println("Hello, Server!");
// 接收服务器的响应
String response = in.readLine();
System.out.println("Server response: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- ServerSocket: ServerSocket 类用于创建服务器套接字,监听客户端的连接请求,并为每个连接创建一个新的 Socket。
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerExample {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
// 接收客户端的数据
String clientInput = in.readLine();
System.out.println("Client says: " + clientInput);
// 发送响应给客户端
out.println("Hello, Client!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. URL 和 HttpURLConnection:
- URL: URL 类用于表示统一资源定位符,可以通过它打开连接、读取数据。
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class URLExample {
public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
// 读取数据
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- HttpURLConnection: HttpURLConnection 类是 URLConnection 的子类,用于处理 HTTP 请求和响应。
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 读取响应
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上是 Java 网络编程的一些基本示例。网络编程涉及到更复杂的概念,如多线程处理、异步编程等。
转载请注明出处:http://www.zyzy.cn/article/detail/436/Java