我使用Node JS创建了一个聊天应用程序,其中我使用Socket.io库在客户机和web服务器之间构建了一个双向连接。
下面是我的代码(创建节点服务器):
// Node Server that will handle Socket io connections
const io = require('socket.io')(3000) // Requiring the socket io Library
const users = {};
io.on("connections", (socket) => {
socket.on("new-user-joined", (name) => {
users[socket.id] = name;
socket.broadcast.emit("user-joined", name)
});
});
socket.on('send', message =>{
socket.broadcast.emit('recieve', {message: message, name: users[socket.id]});
});
我的节点服务器停止并显示此错误:
问题:
PS C:\Users\SANKET PRAKHER\Desktop\complete web development bootcamp\Chat Application\Node Server> nodemon .\index.js
[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node .\index.js`
C:\Users\SANKET PRAKHER\Desktop\complete web development bootcamp\Chat Application\Node Server\index.js:14
socket.on('send', message =>{
^
ReferenceError: socket is not defined
at Object.<anonymous> (C:\Users\SANKET PRAKHER\Desktop\complete web development bootcamp\Chat Application\Node Server\index.js:14:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
您对编写socket.on('send',...
的变量socket的引用只是超出了socket
本身是一个已定义变量的范围。该变量仅在您给出的作为io.on
调用的第二个参数的函数中定义,并且通常应该在该函数中引用。顺便提一下,该函数将其作为名为socket
的参数。
因此您应该在该函数中携带您的scoket.on代码块:
io.on("connections", (socket) => {
socket.on("new-user-joined", (name) => {
users[socket.id] = name;
socket.broadcast.emit("user-joined", name)
});
socket.on('send', message => {
socket.broadcast.emit('recieve', {message: message, name: users[socket.id]});
});
});
就像您对socket.on('new-user-join',...)
所做的一样