如何实现nwjs与socket链接在一起

2025-04-19 09:50:17
推荐回答(1个)
回答1:

可以实现的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

// 创建一个Socket实例
var socket = new WebSocket('ws://localhost:8080');

// 打开Socket
socket.onopen = function(event) {

// 发送一个初始化消息
socket.send('I am the client and I\'m listening!');

// 监听消息
socket.onmessage = function(event) {
console.log('Client received a message',event);
};

// 监听Socket的关闭
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};

// 关闭Socket....
//socket.close()
};

参数为URL,ws表示WebSocket协议。onopen、onclose和onmessage方法把事件连接到Socket实例上。每个方法都提供了一个事件,以表示Socket的状态。