用vert.x 4.0 写一个地址为127.0.0.1:3000的websocket服务器
时间: 2024-02-22 11:00:28 浏览: 131
通过Socket搭建Web服务器
好的,以下是使用 Vert.x 4.0 写一个地址为 127.0.0.1:3000 的 WebSocket 服务器的示例代码:
```java
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.ServerWebSocket;
public class WebSocketServer {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
HttpServer httpServer = vertx.createHttpServer();
httpServer.webSocketHandler(WebSocketServer::handleWebSocketConnection);
httpServer.listen(3000, "127.0.0.1", res -> {
if (res.succeeded()) {
System.out.println("WebSocket server is running on port 3000");
} else {
System.err.println("Failed to start WebSocket server: " + res.cause());
}
});
}
private static void handleWebSocketConnection(ServerWebSocket webSocket) {
System.out.println("WebSocket client connected: " + webSocket.remoteAddress());
// 在这里可以添加处理 WebSocket 消息的逻辑
webSocket.textMessageHandler(msg -> {
System.out.println("Received message from client: " + msg);
webSocket.writeTextMessage("Server received your message: " + msg);
});
webSocket.closeHandler(close -> {
System.out.println("WebSocket client disconnected: " + webSocket.remoteAddress());
});
}
}
```
这个示例代码会启动一个 WebSocket 服务器,监听地址为 127.0.0.1,端口为 3000。当有客户端连接到 WebSocket 服务器时,会输出一条日志,同时会注册一个处理 WebSocket 消息的回调函数。当客户端发送消息时,服务器会将消息内容原样返回给客户端。当客户端断开连接时,也会输出一条日志。
阅读全文