视频推荐
WebSocket 可以实现双向通信,适合实时通信场景。本文介绍一下使用 Javacript 语言开发 AWTK-WEB 应用程序,并用 WebSocket 与服务器通讯。
https://awtk.zlg.cn/web/index.html
这里假设应用程序的名称为 AwtkApplicationJSWebSocket,后面会用到,如果使用其它名称,后面要做相应修改。
2. 编写代码
2.1 删除 src 目录下全部文件(留着也可以,只是看起来比较乱),在 src 目录创建 js 目录。
2.2 在 src/js 下创建 application.js ,内容如下:
function applicationInit() {
home_page_open();
}
applicationInit()
function home_page_open() {
var win = TWindow.open("home_page");
var send = win.lookup("send", true);
var send_text = win.lookup("send_text", true);
var recv_text = win.lookup("recv_text", true);
const ws = new WebSocket("ws://localhost:8090");
send.on(TEventType.CLICK, function (evt) {
const message = send_text.getText();
ws.send(message);
return TRet.OK;
});
ws.onopen = () => {
recv_text.setText("Connected to the server");
};
ws.onmessage = (event) => {
recv_text.setText(event.data);
};
ws.onclose = () => {
recv_text.setText("close");
};
win.layout();
}
注意:控件的名称一定要和 home_page.xml 保持一致。
3. 在 AWTK Designer 中,执行“打包” “编译” “模拟运行”
https://github.com/zlgopen/awtk/blob/master/docs/build_config.md
这里给出一个例子,可以在此基础上进行修改,该文件位于:
{
"name": "AwtkApplicationJSWebSocketWebSocket",
"version": "1.0",
"app_type":"js",
"author": "xianjimli@hotmail.com",
"copyright": "Guangzhou ZHIYUAN Electronics Co.,Ltd.",
"themes":["default"],
"sources": [
"src/js/*.js"
]
}
./build_win32.sh examples/AwtkApplicationJSWebSocket/build.json release
./build_linux.sh examples/AwtkApplicationJSWebSocket/build.json release
./build_mac.sh examples/AwtkApplicationJSWebSocket/build.json release
请根据应用程序所在目录,修改配置文件的路径。
./start_web.sh
start_web_debug.sh
进入 awtk-web 目录下的 tools/websocket,执行:
node websocket_echo_server.js