移动端与VirtualBox中Ubuntu服务器的JSON通信及IP配置技术问询
刚好我之前折腾过类似的场景,分两部分给你讲明白——先搞定最关键的IP问题,再聊JSON双向通信的具体实现,都是实战能用的方案。
一、VirtualBox Ubuntu的正确IP选择
要让移动应用能访问到VirtualBox里的Ubuntu服务器,核心是让两者处于同一局域网,具体操作如下:
- 第一步:切换VirtualBox网络模式为桥接模式(Bridged Adapter)
打开VirtualBox,选中你的Ubuntu虚拟机 → 点击「设置」→ 「网络」→ 把网络连接方式改成「桥接适配器」,界面选择你当前Windows正在使用的网卡(比如WiFi网卡或者有线网卡)。这样Ubuntu会直接接入你的局域网,和Windows、移动设备处于同一网段。 - 第二步:获取Ubuntu的局域网IP
打开Ubuntu终端,输入命令:ip addr show,找到带有inet字段的网卡(通常是enp0s3或enp0s8),后面的xxx.xxx.xxx.xxx就是服务器的局域网IP。比如输出里的inet 192.168.1.105/24,那192.168.1.105就是你要用到的地址。 - 验证连通性:在Windows的cmd里输入
ping 你的UbuntuIP,如果能通就说明网络没问题。另外记得在Ubuntu里开放你要用到的端口(比如ufw allow 5000),Windows防火墙也别挡住这个端口。
二、JSON双向通信的实现方案
这里分两种常见场景:一种是请求响应式的双向数据交互(客户端发JSON请求,服务器返回JSON响应),另一种是实时双向推送(比如聊天、实时数据更新),分别给你讲实操步骤:
1. 请求响应式(基于HTTP API)
服务器端(Ubuntu):用Python Flask快速搭建轻量API
Flask上手快,适合快速搭建JSON接口:
- 先安装依赖:
pip install flask - 写一个极简的API示例:
from flask import Flask, request, jsonify app = Flask(__name__) # 接收客户端JSON请求并返回JSON响应 @app.route('/api/exchange-data', methods=['POST']) def exchange_data(): # 解析客户端发送的JSON数据 client_json = request.get_json() print(f"收到客户端数据:{client_json}") # 模拟数据处理逻辑 response_json = { "status": "success", "msg": "已接收你的请求", "processed_result": client_json.get("input_content", "") + "_handled" } # 返回JSON格式响应 return jsonify(response_json) if __name__ == '__main__': # host设为0.0.0.0才能让外部设备访问 app.run(host='0.0.0.0', port=5000, debug=True)
运行这个脚本,Ubuntu的API服务器就启动在5000端口了。
移动客户端(以Android为例):用OkHttp发送/解析JSON
Android端用OkHttp处理HTTP请求很方便,配合Gson解析JSON:
- 先在
build.gradle添加依赖:
implementation 'com.squareup.okhttp3:okhttp:4.12.0' implementation 'com.google.code.gson:gson:2.10.1'
- 写发送JSON请求的代码:
import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import com.google.gson.Gson; // 定义客户端数据类 class ClientRequest { String input_content; public ClientRequest(String content) { this.input_content = content; } } // 定义服务器响应类 class ServerResponse { String status; String msg; String processed_result; } // 发送JSON请求的方法 public void sendJsonRequest() { OkHttpClient client = new OkHttpClient(); MediaType JSON_TYPE = MediaType.get("application/json; charset=utf-8"); // 构造要发送的JSON数据 ClientRequest requestData = new ClientRequest("hello_from_mobile_app"); String jsonStr = new Gson().toJson(requestData); RequestBody requestBody = RequestBody.create(jsonStr, JSON_TYPE); Request request = new Request.Builder() .url("http://192.168.1.105:5000/api/exchange-data") // 替换成你的Ubuntu IP和端口 .post(requestBody) .build(); // 异步发送请求(避免阻塞主线程) client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(okhttp3.Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseJson = response.body().string(); ServerResponse serverResp = new Gson().fromJson(responseJson, ServerResponse.class); // 处理服务器返回的数据 System.out.println("服务器回复:" + serverResp.msg); } } }); }
iOS端可以用Alamofire实现类似逻辑,核心都是构造JSON请求、发送到服务器IP、解析返回的JSON。
2. 实时双向推送(基于WebSocket)
如果需要客户端和服务器随时双向发消息(比如实时聊天、数据同步),用WebSocket比HTTP轮询高效得多。
服务器端(Ubuntu):用Flask-SocketIO实现WebSocket
- 安装依赖:
pip install flask-socketio - 示例代码:
from flask import Flask from flask_socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' # 允许跨域,移动端不用太担心,但加上更稳妥 socketio = SocketIO(app, cors_allowed_origins="*") # 监听客户端连接事件 @socketio.on('connect') def handle_connect(): print('客户端已连接') emit('server_msg', {'content': '欢迎连接到实时服务器'}) # 监听客户端发送的JSON消息 @socketio.on('client_msg') def handle_client_msg(data): print(f"收到客户端实时消息:{data}") # 回复客户端 emit('server_msg', {'content': f'已收到你的消息:{data.get("content")}'}) if __name__ == '__main__': socketio.run(app, host='0.0.0.0', port=5000, debug=True)
移动客户端(Android):用Socket.IO客户端连接
- 添加依赖:
implementation 'io.socket:socket.io-client:2.0.0'
- 实现双向通信代码:
import io.socket.client.IO; import io.socket.client.Socket; import io.socket.emitter.Emitter; import org.json.JSONObject; public class WebSocketManager { private Socket mSocket; { try { // 替换成你的Ubuntu IP和端口 mSocket = IO.socket("http://192.168.1.105:5000"); } catch (Exception e) { e.printStackTrace(); } } public void startConnection() { mSocket.connect(); // 监听服务器发送的实时消息 mSocket.on("server_msg", new Emitter.Listener() { @Override public void call(Object... args) { JSONObject msgData = (JSONObject) args[0]; try { String content = msgData.getString("content"); // 处理服务器消息 System.out.println("实时消息:" + content); } catch (Exception e) { e.printStackTrace(); } } }); // 发送实时消息到服务器 JSONObject sendData = new JSONObject(); try { sendData.put("content", "hello from mobile via websocket"); mSocket.emit("client_msg", sendData); } catch (Exception e) { e.printStackTrace(); } } public void stopConnection() { mSocket.disconnect(); } }
最后几个注意点
- 确保移动设备和Windows、Ubuntu连同一个WiFi(同一局域网)。
- Android 9及以上默认禁止明文HTTP请求,需要在
AndroidManifest.xml里添加android:usesCleartextTraffic="true",或者给服务器配置HTTPS。 - 测试时先在Windows浏览器用Postman之类的工具调用API,确认服务器正常,再在移动应用里测试。
内容的提问来源于stack exchange,提问作者Spade
相关产品推荐
相关产品推荐

