我阅读了本网站上的很多好文章,并始终找到正确的答案,但是经过几天的尝试,我不得不最终问出我的第一个问题。
问题:总而言之,我在传递newusername时遇到麻烦,因为它是在用户加入时出现的。它总是作为[对象对象]传递,据我所读,是因为它试图传递不是字符串的变量。此外,每次用户聊天时,它都会不断传递。我设法在名为sendMessage()的函数中传递了newusername,并且可以正常工作,但通过其他任何函数(如send_message(event))传递时,username却没有通过。
聊天应用
<div id="chat-container">
<pre id="chat-box"></pre>
<div id="message-bar-container">
<label>Your name: <span id='label_name'>Default</span></label>
<input id="message" onkeypress="send_message(event)">
<button id="send-btn">Send</button>
</div>
</div>
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<script src="/socket-io/socket.io.js"></script>
<script>
var server = io();
var username = 'default';
var newusername = [];
server.on('connect', function (s) {
let username = JSON.stringify('Guest_' + (server.id)[0] + (server.id)[1] + (server.id)[2]);
newusername.push(username);
var url = new URL(location.href);
room = url.searchParams.get('room') || 'main-room';
server.emit('join-room', room, newusername);
document.getElementById("label_name").innerHTML = username;
console.log('connected to room: ', room, username);
});
//the display name
server.on('chat-msg', function (msg) {
var chat = document.getElementById("chat-box");
chat.insertAdjacentHTML('beforeend', '\n' + msg, 'username');
});
//create sendMessage function to send the incoming user text to the room.
function sendMessage() {
var msg = document.getElementById("message");
server.emit('incoming', newusername)
}
//create a send_message function to send the incoming user to sendMessage() if user pressed '13' aka enter.
function send_message(event) {
var char = event.which || event.keyCode;
if (char == '13') {
let msg = document.getElementById('message');
server.emit('incoming', {room: room, msg: msg.value, newusername})
msg.value = '';
sendMessage();
}
}
//when the send button is clicked it calls sendMessage()
document.getElementById('send-btn').onclick = function () {
sendMessage();
}
</script>
<!--create your own middleware to save all the chat messages and time stamp 'let today =new Date'-->
**
** 该代码还以“ 已加入新用户”的形式传递,并且在客户/用户加入频道时也以[对象对象]的形式传递。
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ROOMS = {};
var index = require('./routes/index');
var users = require('./routes/users');
var app = express(); //first build the app.
var http = require('http').Server(app); //call http in order to create a connection pipeline.
var io = require('socket.io')(http); //call http and io in before app = express()
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/socket-io',
express.static('node_modules/socket.io-client/dist'));
//
//emit message once user connects to the socket.
io.on('connection', function(client){
console.log('Connectioned to ', client.id);
//emit message once user leaves the socket.
client.on('disconnect', function () {
console.log('User has disconnected.');
});
client.on('incoming', function(msg){
io.emit('chat-msg', msg);
});
//joining a room.
client.on('join-room', function(room, username){
client.join(room, function() {
console.log(client.rooms);
let msg = {msg: '**new user joined**', user: 'SERVER'};
io.to(room).emit('chat-msg', {msg, username});
});
client.on('incoming', function(msg) {
io.to(msg.room).emit('chat-msg', msg.msg);
});
});
});
var PORT = process.env.PORT || 8000;
http.listen(PORT, function () { //since we're using web socket, it will not be app.listen, but instead http.listen
console.log('Listening on port ' +PORT);
});
//set up landing page which allows you to select chatroom or create your own chatroom.
//set up multi chatroom functions.
//set up user-id for chatrooms.