I'm trying to make a chat program using electron.js and socket.io, but while my socket.io code works perfectly when I test it in the console or browser, once I load it into electron code the sockets only connect, they can't receive or emit data.
(我正在尝试使用electron.js和socket.io创建一个聊天程序,但是当我在控制台或浏览器中对其进行测试时,虽然socket.io代码可以完美运行,但一旦将其加载到电子代码中,则套接字只能连接,但它们无法接收或发出数据。)
Here's my code
(这是我的代码)
server.js
(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 (Client)
(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 (For loading electron)
(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 (Test client in console that works)
(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);
});
ask by shadowsinger translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…