我正在尝试使用electron.js和socket.io创建一个聊天程序,但是当我在控制台或浏览器中测试时,我的socket.io代码工作正常,一旦我将它加载到电子代码中,只有套接字连接,他们无法接收或发送数据。
这是我的代码
server.js
var port = 8321
var io = require('socket.io').listen(port);
console.log('listening on *:' + port);
io.on('connection', function(socket) {
console.log('a user connected');
io.emit('bar', "Greetings from the server");
socket.on('chat_message', function(msg1) {
console.log(msg1);
socket.emit('chat_message', "Reply from server");
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
view.js(客户端)
let $ = require('jquery')
$('#messages').append($('<li>').text("Initial setup"));
const io = require('socket.io-client');
var socket = io.connect('http://localhost:8321');
$('form').submit(function(){
var msg = $('#m').val();
if (!msg) {
return false;
}
socket.emit('chat_message', msg);
$('#messages').append($('<li>').text("You sent: "+msg));
window.scrollTo(0, document.body.scrollHeight);
$('#m').val('');
return false;
});
socket.on('bar', function(msg){
$('#messages').append($('<li>').text("Received: "+msg));
window.scrollTo(0, document.body.scrollHeight);
});
index.js(用于加载电子)
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
transparent : true,
frame:false
})
mainWindow.setAlwaysOnTop(true);
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
mainWindow.setIgnoreMouseEvents(true);
}
app.on('ready', createWindow)
client1.js(在运行的控制台中测试客户端)
var io2 = require('socket.io-client');
var socket2 = io2.connect('http://localhost:8321');
var msg2 = "Greetings from client1";
socket2.emit('chat_message', msg2);
socket2.on('bar', function(msg){
console.log('Received message from server:' + msg);
});
答案 0 :(得分:0)
我使用您的代码向我的Github帐户添加了一个完整的用例示例 并每2秒钟从服务器发送一次消息
setInterval(()=>{
io.emit('bar', "Greetings from the server");
},2000)
https://github.com/ntedgi/sof-socket.io
git clone https://github.com/ntedgi/sof-socket.io.git
npm install
node server.js
npm run start
输出: