Commonly used protocols and libraries for Java network programming: Protocols: TCP, UDP, HTTP, HTTPS, FTP Library: java.net, java.nio, Apache HttpClient, Netty, OkHttp
Commonly used protocols and libraries in Java network programming
Java provides a wealth of libraries and frameworks to simplify network programming. Some commonly used protocols and libraries are listed below:
Protocol
Library
Practical case
Send HTTP GET request
import java.net.HttpURLConnection; import java.net.URL; public class HttpGetExample { public static void main(String[] args) throws Exception { String url = "https://www.example.com"; // 创建 HttpURLConnection URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法和内容类型 con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json"); // 发送请求并获取响应代码 int responseCode = con.getResponseCode(); // 打印响应正文 System.out.println("Response Code: " + responseCode); Scanner scanner = new Scanner(con.getInputStream()); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } scanner.close(); } }
Create TCP server
import java.net.ServerSocket; import java.net.Socket; public class TcpServerExample { public static void main(String[] args) throws Exception { // 监听端口 int port = 8080; // 创建 ServerSocket ServerSocket serverSocket = new ServerSocket(port); // 循环等待客户端连接 while (true) { // 接受客户端连接 Socket clientSocket = serverSocket.accept(); // 创建新线程处理客户端连接 Thread thread = new Thread(() -> { try { // 获取客户端输入流 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // 打印客户端发来的数据 String line; while ((line = in.readLine()) != null) { System.out.println("Message from client: " + line); } } catch (Exception e) { e.printStackTrace(); } }); thread.start(); } } }
The above is the detailed content of What are the commonly used protocols and libraries in Java network programming?. For more information, please follow other related articles on the PHP Chinese website!