在 Java 中“搭建网络服务”通常指提供可被其他程序或浏览器访问的服务,最常见的是:
下面按常见程度从简单到工程化给你讲。
适合:学习网络原理、自定义协议
import java.io.*;
import java.net.*;
public class TcpServer {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8080);
System.out.println("服务启动,端口 8080");
while (true) {
Socket socket = server.accept();
new Thread(() -> {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String msg = in.readLine();
System.out.println("收到:" + msg);
out.println("服务器回复:" + msg);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
Socket socket = new Socket("localhost", 8080);
可以使用:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello Network Service";
}
}
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
访问:
http://localhost:8080/hello
✅ 优点:
适合:轻量工具
import com.sun.net.httpserver.*;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/hello", exchange -> {
String resp = "Hello";
exchange.sendResponseHeaders(200, resp.length());
exchange.getResponseBody().write(resp.getBytes());
exchange.close();
});
server.start();
}
}
适合:聊天、推送
@ServerEndpoint("/ws")
@Component
public class WebSocketServer {
@OnMessage
public void onMessage(Session session, String msg) throws IOException {
session.getBasicRemote().sendText("收到:" + msg);
}
}
前端连接:
ws://localhost:8080/ws
| 需求 | 推荐方案 |
|---|---|
| 学习网络 | Socket |
| 接口服务 | Spring Boot |
| 轻量工具 | HttpServer |
| 实时通信 | WebSocket |
| 高性能 | Netty |
你可以告诉我:
“我想做什么类型的网络服务?”
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。