- 使用示范
send发送后会同步返回发送后服务器的响应消息
- 依赖
- websocket
安装websocket:npm install websocket
安装过程可能需要你安装python vs等如果报错看报错信息把需要的依赖安装即可
- 组件代码
const WebSocketClient = require('websocket').client;
/*
连接websocket
*/
let connect=function(url){
return new Promise((resolve => {
//建立连接
let client = new WebSocketClient();
//连接失败
client.on('connectFailed', function(error) {
console.log('Connect Error, ' + error.toString());
});
//开始连接
client.on('connect', function(connection) {
console.log('开始连接'+url);
connection.on('error', function(error) {
console.log("连接错误 " + error.toString());
});
connection.on('close', function() {
console.log('连接关闭');
});
connection.on('message', function (message) {
connection.resolveFunc(message)
});
if (connection.connected) {
console.log('websocket连接已建立')
resolve(connection)
}
});
client.connect(url)
}))
}
/*
发送消息并获得结果
*/
let send=function (conn,msg) {
return new Promise((resolve => {
conn.sendUTF(msg)
conn.resolveFunc=resolve
}))
}
/*
关闭连接
*/
let close=function(conn){
conn.close()
}
module.exports={
connect:connect,
send:send,
close:close
}
- 调用代码
const util=require('./AsyncWebsocketUtil')
async function main() {
let conn=await util.connect('wss://api.yourhost.pr/ws')
let respMsg=await util.send(conn,'1')
console.log(respMsg)
}
main()