我是Node.js的新手,使用socket.id来识别客户端登录用户的问题,使用电子邮件ID和密码从服务器端的表中验证,如果验证,则使用用户socket.id向该客户发送用户名。
当两个用户登录时,他们可以与唯一的用户名聊天,但是当刷新聊天页面时,两个用户名都被更改为第二次登录的用户名(即稍后登录的用户)。请帮忙。
这是我的代码:
server.js
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server)
, os = require('os')
, open = require('open')
, bodyParser = require('body-parser')
, connect = require('connect')
, mysql = require("mysql");
var clients = {};
server.listen(9383,'192.168.1.3');
app.get('/loginstyle.css', function (req, res) {
res.sendfile(__dirname + '/loginstyle.css');
});
app.get('/loginme', function (req, res) {
res.sendfile(__dirname + '/loginmysql.html');
});
app.get('/option', function (req, res) {
res.sendfile(__dirname + '/option.html');
});
app.get('/chat', function (req, res) {
res.sendfile(__dirname + '/chat.html');
});
app.post('/valid', function (req, res) {
var username=req.body.email;
var password=req.body.pass;
var connection = mysql.createConnection({
"hostname": "localhost",
"user": "root",
"password": "vk123",
"database": "login"
});
connection.connect();
connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){
if (err){
throw err;
}else{
var name1=rows[0].name;
io.sockets.on('connection', function(socket){
clients[socket.id] = socket;
clients[socket.id].emit('name', name1); // username is sent to client
});
res.redirect('http://192.168.1.3:9383/chat');
}
});
connection.end();
});
io.sockets.on('connection', function(socket){
socket.on('chat message', function(name,msg){
console.log(msg);
io.emit('chatmessage',name,msg);
});
});
client.html
<!DOCTYPE html>
<html>
<head>
</head>
<body background="/bgimage.jpg">
<div class="chat"></div>
<form style="bottom:10px; position:fixed; padding-left: 100px">
<input type="text" class="msg" style="width:1000px; height:30px"></input>
<button type="submit" class="enter" style="padding-left:0px; height:35px; background-color:skyblue">Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://192.168.1.3:9383');
var username;
var chatmsg=[];
socket.on('name', function(name){
username=name;
console.log(username);
});
$('.enter').bind("click",function(){
chatmsg.push({chatname:username, msgtext:($('.msg').val())});
socket.emit('chat message',username,$('.msg').val() );
$('.msg').val('');
return false;
});
socket.on('chatmessage', function(name,msg){
var block= $("<div class='message'> </div>");
if(msg.length){
var messenger= $("<div style='color:green;font-weight:bold;background-color:floralwhite'> </div>");
messenger.append(name);
block.append(messenger);
var text=$("<div style='padding:3px;background-color:floralwhite'></div>");
text.append(msg);
block.append(text);
block.append($("<div style='padding:10px;background-color:transparent'></div>"));
$('.chat').append(block);
}
});
});
</script>
</body>
</html>
答案 0 :(得分:0)
Index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var _mysql = require('mysql');
var HOST = 'localhost';
var PORT = 3306;
var MYSQL_USER = 'root';
var MYSQL_PASS = '';
var DATABASE = 'library';
var TABLE = 'chat';
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
var mysql = _mysql.createConnection({
host: HOST,
port: PORT,
user: MYSQL_USER,
password: MYSQL_PASS,
});
mysql.query('use ' + DATABASE);
socket.on('chat message', function(from, msg){
if(from != 'System'){
io.emit('chat message', from, msg);
}
});
socket.on('notifyUser', function(user){
io.emit('notifyUser', user);
});
socket.on('saveUser', function(from, msg){
mysql.query("insert into "+ TABLE +" (send_from, send_message) values ('"+from+"','"+msg+"')",
function selectCb(err, results, fields) {
if (err) throw err;
});
});
socket.on('display', function(){
mysql.query("select * from "+ TABLE +" order by (chat_id) asc ",
function selectCb(err, rows, fields) {
io.emit('display', rows);
//console.log(rows);
});
});
});
http.listen(81, function(){
console.log('listening on *:3000');
});
的index.html
<?php session_start(); ?>
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
$(document).ready(function(){
var data_name = sessionStorage.getItem('name');
if(data_name){
var name = data_name;
$('#user').val(name);
}else{
var name = makeid();
var hello = sessionStorage.setItem('name', name);
$('#user').val(name);
}
socket.emit('chat message', 'System', '<b>' + name + '</b> has joined the discussion');
$('form').submit(function(){
var from = $('#user').val();
var message = $('#m').val();
if(message != '') {
socket.emit('chat message', from, message);
$('#m').val('').focus();
}
return false;
});
socket.on('chat message', function(from, msg){
var me = $('#user').val();
if(from == me){
socket.emit('saveUser', me, msg);
}
var color = (from == me) ? 'green' : '#009afd';
var from = (from == me) ? 'Me' : from;
$('#messages').append('<li><b style="color:' + color + '">' + from + '</b>: ' + msg + '</li>');
});
socket.emit('display');
socket.on('display', function(results){
var me = $('#user').val();
$('#messages').html('');
$.each( results, function( key, value ) {
var from = value.send_from;
var color = (from == me) ? 'green' : '#009afd';
var from = (from == me) ? 'Me' : from;
$('#messages').append('<li><b style="color:' + color + '">' + from + '</b>: ' + value.send_message + '</li>');
});
});
socket.on('notifyUser', function(user){
var me = $('#user').val();
if(user != me) {
$('#notifyUser').text(user + ' is typing ...');
}
setTimeout(function(){ $('#notifyUser').text(''); }, 10000);
});
});
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
</script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages">
<?php
$conn = mysqli_connect('localhost','root','','library');
?>
</ul>
<form action="">
<input type="hidden" id="user" />
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>