在Java中搭建简单服务器
在Java中搭建一个简单的服务器有多种方法,以下是几种常见的方式:
1. 使用Java原生Socket API
import java.io.*;
import java.net.*;
public class SimpleServer {
public static void main(String[] args) throws IOException {
// 创建服务器Socket,监听8080端口
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("服务器启动,等待客户端连接...");
while (true) {
// 等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("客户端已连接: " + clientSocket.getInetAddress());
// 获取输入输出流
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// 读取客户端请求
String request = in.readLine();
System.out.println("收到请求: " + request);
// 发送响应
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("rn");
out.println("<html><body><h1>Hello from Java Server!</h1></body></html>");
// 关闭连接
clientSocket.close();
}
}
}
2. 使用Java内置的HttpServer (JDK 6+)
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
public class SimpleHttpServer {
public static void main(String[] args) throws IOException {
// 创建HTTP服务器,监听8080端口
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
// 创建上下文和处理程序
server.createContext("/", exchange -> {
String response = "<html><body><h1>Hello from Java HttpServer!</h1></body></html>";
exchange.sendResponseHeaders(200, response.length());
exchange.getResponseBody().write(response.getBytes());
exchange.close();
});
// 启动服务器
server.start();
System.out.println("服务器已启动,访问 http://localhost:8080");
}
}
3. 使用轻量级框架Spark Java
首先添加依赖(Maven):
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.9.4</version>
</dependency>
然后编写代码:
import static spark.Spark.*;
public class SparkServer {
public static void main(String[] args) {
// 设置端口
port(8080);
// 定义路由
get("/", (req, res) -> "Hello from Spark Java!");
// 启动服务器
System.out.println("服务器已启动,访问 http://localhost:8080");
}
}
4. 使用Spring Boot (更完整的企业级解决方案)
添加依赖(Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.0</version>
</dependency>
编写代码:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringBootServer {
public static void main(String[] args) {
SpringApplication.run(SpringBootServer.class, args);
}
@GetMapping("/")
public String hello() {
return "Hello from Spring Boot!";
}
}
选择建议
- 对于学习网络编程基础,推荐使用原生Socket API
- 对于简单HTTP服务,HttpServer或Spark Java是不错的选择
- 对于生产环境或复杂应用,Spring Boot是最佳选择
以上每种方法都可以扩展为更复杂的服务器应用,根据你的需求选择最适合的方案。
云服务器