我是Node JS的新手,我是新手,几天来,我一直在查看Node JS代码,然后尝试实现它,出于知识目的,我开始在Node JS中使用socket.io构建聊天应用程序。 。我遇到了一个人的代码,该人是MEAN堆栈的用户,因为我在其中使用mysql,node,express和简单的html。
这包括3个部分。我试图尽可能地遵循代码,并愉快地配置了我的注册和登录,路由部分。
但是现在当我不得不在用户之间发送消息时,我陷入了困境,起初,我只想制作类似于socket.io教程的群聊应用程序,这个家伙正在使用Class,所以我跟随他,因为他们提供了很好的数据抽象。
I tried to invoke socket class object using require in chat.html but i found require not defined
I tried using script src="file path" but it is saying file not found
Folder structure
*client* (public)
---> js
---> css
---> views
---> index.html
*utils*
---> config.js
---> db.js
---> socket.js
---> helper.js
---> routes.js
server.js
package.json
node modules.
我知道如何使用类,但是在文件中包含文件时遇到了困难。感谢您的帮助
'use strict';
const express = require("express");
const http = require('http');
const socketio = require('socket.io');
const bodyParser = require('body-parser');
const routes = require('./utils/routes');
const config = require('./utils/config');
Server.js Class Server()
constructor() {
this.port = process.env.port || 9000;
this.host = process.env.HOST || 'localhost';
this.app = express();
// const http = require('http').Server(this.app);
// const io = require('socket.io')(http);
this.http = http.Server(this.app);
// Node js server library
// const io = require('socket.io')(http);
this.socket = socketio(this.http);
}
appConfig() {
this.app.use(
bodyParser.json()
);
this.app.use(
bodyParser.urlencoded({ extended: true })
);
new config(this.app); // This code invokes config class constructor
}
/* Including app Routes starts*/
`includeRoutes`() {
new routes(this.app, this.socket).`routesConfig`();
}
/* Including app Routes ends*/
appExecute() {
this.appConfig();
this.includeRoutes();
// console.log(1);
this.http.listen(this.port, this.host, () => {
console.log(`Listening on http://${this.host}:${this.port}`);
});
}}
const app = new Server();
app.appExecute();
Routes.js
'use strict';
const helper = require('./helper');
const path = require('path');
const validator = require('validator')
const Socket = require('./socket');
class Routes {
constructor(app, socket) {
this.app = app;
this.io = new Socket(socket); // I configures this line, it was not making sense earlier;// this.io = socket;
}
appRoutes() {
this.app.post('/usernameCheck', async (request, response) => {
const username = request.body.username;
if (username === "" || username === undefined || username === null) {
response.status(412).json({
error: true,
message: `username cant be empty.`
});
} else {
const data = await helper.userNameCheck(username.toLowerCase());
if (data[0]['count'] > 0) {
response.status(401).json({
error: true,
message: 'This username is alreday taken.'
});
} else {
response.status(200).json({
error: false,
message: 'This username is available.'
});
}
}
});
this.app.post('/registerUser', async (request, response) => {
const registrationResponse = {}
const data = {
email: request.body.email.toLowerCase(),
password: request.body.password
};
if (data.email === '' || !validator.isEmail(data.email)) {
registrationResponse.error = true;
registrationResponse.message = `Empty or incorrect email.`;
response.status(412).json(registrationResponse);
} else if (data.password === '') {
registrationResponse.error = true;
registrationResponse.message = `password cant be empty.`;
response.status(412).json(registrationResponse);
} else {
const result = await helper.registerUser(data);
if (result === null) {
registrationResponse.error = true;
registrationResponse.message = `User registration unsuccessful,try after some time.`;
response.redirect('/chat');
// response.status(417).json(registrationResponse);
} else {
registrationResponse.error = false;
registrationResponse.userId = result.insertId;
registrationResponse.message = `User registration successful.`;
response.status(200).json(registrationResponse);
}
}
});
this.app.post('/login', async (request, response) => {
const loginResponse = {}
const data = {
email: (request.body.email).toLowerCase(),
password: request.body.password
};
if (data.email === '' || data.email === null) {
loginResponse.error = true;
loginResponse.message = `email cant be empty.`;
response.status(412).json(loginResponse);
} else if (data.password === '' || data.password === null) {
loginResponse.error = true;
loginResponse.message = `password cant be empty.`;
response.status(412).json(loginResponse);
} else {
const result = await helper.loginUser(data);
if (result === null || result.length === 0) {
loginResponse.error = true;
loginResponse.message = `Invalid username and password combination.`;
response.status(401).json(loginResponse);
} else {
loginResponse.error = false;
loginResponse.userId = result[0].id;
loginResponse.message = `User logged in.`;
response.redirect('/chat');
// response.status(200).json(loginResponse);
}
}
});
this.app.get('/chat', (request, response) => {
response.sendFile(path.join(__dirname + '../../client/views/chat.html'));
});
this.app.get('/', (request, response) => {
response.sendFile(path.join(__dirname + '../../client/index.html'));
});
this.app.get('/login', (request, response) => { response.sendFile(path.join(__dirname+'../../client/views/login.html'));
});
}
routesConfig() { // routes function
this.appRoutes();
}
}
module.exports = Routes;
I have a file under utils folder Socket.js
'use strict';
const path = require('path');
const helper = require('./helper');
class Socket{
constructor(socket){
this.io = socket;
}
socketEvents(){
this.io.on('connection', (socket) => {
/**
* get the user's Chat list
*/
});
socket.on('add-message', async (data) => {
if (data.message === '') {
this.io.to(socket.id).emit(`add-message-
response`,`Message cant be empty`);
}else if(data.fromUserId === ''){
this.io.to(socket.id).emit(`add-message-response`,`Unexpected error, Login again.`);
}else if(data.toUserId === ''){
this.io.to(socket.id).emit(`add-message-response`,`Select a user to chat.`);
}else{
let toSocketId = data.toSocketId;
const sqlResult = await helper.insertMessages({
fromUserId: data.fromUserId,
toUserId: data.toUserId,
message: data.message
});
this.io.to(toSocketId).emit(`add-message-response`, data);
}
});
socket.on('clientConnected', function (msg) {
alert(1);
// We can also emit events from the client.
// To emit an event from your client, use the emit function on the socket object in client side.
// To handle these events, use the on function on the socket object on your server.
console.log(socket.id);
//Sever event emitter
io.emit('user connected', msg);
})
}
socketConfig(){
this.io.use( async (socket, next) => {
let userId = socket.request._query['userId'];
let userSocketId = socket.id;
const response = await helper.addSocketId( userId, userSocketId);
if(response && response !== null){
next();
}else{
console.error(`Socket connection failed, for user Id ${userId}.`);
}
});
this.socketEvents();
}
}
module.exports = Socket;
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" />
<button>Send</button>
</form>
</body>
</html>
<script src="../socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io().connect(window.location.host);
$(document).ready(function () {
socket.emit('clientConnected', 'User connected');
});
socket.on('user connected', function (msg) {
$('#messages').append($('<li>').text(msg));
});
socket.on('connect_error', function () {
console.log('Failed to connect to server');
});
$('form').submit(function (e) {
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function (msg) {
$('#messages').append($('<li>').text(msg));
});
});
</script>