Я работаю над простым чатом для меня и группы друзей.Я сделал это с помощью socket.io, nodeJS, HTML5 JavaScript и CSS.Я хотел добавить функцию прозвища, чтобы я знал, кто есть кто.Пока у меня есть это (я знаю, что это грязно, как только оно заработает, я приведу его в порядок):
index.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.emit('chat message', msg);
});
socket.on('name input', function(nme){
console.log('Login: ' + nme);
io.emit('name input', nme);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
chat.html:
<!doctype html>
<html>
<head>
<title>TheChatWeb || Web Edition 0.0.2</title>
<style>
@import url('https://fonts.googleapis.com/css?family=Heebo:900');
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; background: #bcbcbc; }
form { padding: 10px; position: fixed; bottom: 0; width: 100%;}
form input { border: 0; padding: 10px; width: 90%; border-top-left-radius: 25px; border-bottom-left-radius: 25px; border-right-style: none; margin-right: 0%; }
form button { width: 9%; background: #d9d9d9; border-size: 2%; border-style: solid; border-color: #c1c1c1; border-top-right-radius: 25px; border-bottom-right-radius: 25px; padding: 10px; margin-left: 0%; }
#messages { list-style-type: none; margin: 5%; padding: 10px; border-style: solid; border-color: #32CD32; border-radius:20px; background: #d9d9d9; }
#messages li { padding: 5px 10px; border-radius: 10px; }
#messages li:nth-child(odd) { background: #eee; }
ul{ position: relative; }
html {
scroll-behavior: smooth;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
</style>
</head>
<body>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<input placeholder="Enter your nickname here!" id="nameField" autocomplete="off" minlength="3" maxlength="15"/><button id="nameGo">Go!<button>
</div>
</div>
<div style="text-align:center;item-align:center;font-family: 'Heebo', sans-serif;font-size:180%;">
TheChatWeb <hr style="margin-left:35%;" color="blue" size="1px" width="30%"> Web Edition 0.0.2
</div>
<ul id="messages"></ul>
<form action="">
<input placeholder="Enter your message here!" id="m" autocomplete="off" minlength="2" maxlength="185"/><button>Send</button>
<div id="char-count"></div>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("nameGo");
// When the page loads, open the modal
document.addEventListener("DOMContentLoaded", function(){
modal.style.display = "block";
});
$(function () {
var uname;
var socket = io();
$('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(uname + ": " + msg));
window.scrollTo(0,document.body.scrollHeight);
});
socket.on('user connected', function(notify){
$('#messages').append($('<li>').text(notify));
window.scrollTo(0,document.body.scrollHeight);
});
socket.on('user disconnected', function(notify){
$('#messages').append($('<li>').text(notify));
window.scrollTo(0,document.body.scrollHeight);
});
socket.on('name input', function(nme){
$('#messages').append($('<li>').text(nme + " joined the chat! Say hi!"));
uname = nme;
window.scrollTo(0,document.body.scrollHeight);
});
btn.onclick = function() {
modal.style.display = "none";
socket.emit('name input', $('#nameField').val());
}
});
</script>
</html>
Теперь моя проблема заключается в том, что если я запускаю это с помощью "node index.js" в PowerShell, он работает нормально, пока кто-то еще не войдет в систему, тогда мое имя пользователя также изменится на их.Мне интересно, есть ли способ сохранить имена пользователей только на стороне клиента, а не отправлять их всем, как сейчас.Любая и вся помощь очень ценится, спасибо!
(Да, я новичок в этом, это мое первое приложение NodeJS, пожалуйста, будьте добры ?.)
Мой index.js с решением @ ChrisG:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var users = {};
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.emit('chat message', msg);
});
socket.on('name input', function(nme){
console.log('Login: ' + nme);
users[socket.id] = { name: nme };
io.emit('name input', nme);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});