Я пытаюсь понять, как работает websocket.js, создав приложение для веб-чата с регистрационной формой.Я создаю кодовый блок
var con = request.accept(null, req.origin);
var id = count++;
clients[id]=con;
, и когда я отправляю текст пользователя на сервер, сервер понимает, какой он пользователь, и отправляет ответ на мой интерфейс.Я не понимаю, как он понимает, какое сообщение написано каким клиентом.
Если вы можете объяснить мне рабочий процесс, я буду признателен.Так как я новый ученик, это трудно понять.
Это мой полный код сервера:
var webSocketServer = require('websocket').server;
var http = require('http');
var count = 0;
var clients = {};
var users = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "123456",
database: "web-chat"
});
var server = http.createServer(function (request, response) {
console.log((new Date())+' Received request for '+request.url);
response.writeHead(404);
response.end();
});
server.listen(1337, function () {
console.log((new Date())+'Server listens on port 1337');
});
wsServer = new webSocketServer({
httpServer: server
});
con.connect(function (err) {
if (err) throw err;
console.log("DB connected.");
wsServer.on('request', function (request) {
console.log((new Date())+'New connect request received'+request.remoteAddress);
var connection = request.accept(null, request.origin);
console.log((new Date()) + 'Connection accepted');
var id = count++;
clients[id] = connection;
connection.on('message', function (message) {
var parsedMsg = JSON.parse(message.utf8Data);
var to = parsedMsg.to;
if(to=='login') {
var userid = parsedMsg.uid;
var password = parsedMsg.pass;
console.log(userid+ " " +password+ "to:"+to);
con.query("SELECT * FROM user_table WHERE userid='" + userid + "' AND password='" + password + "'",
function (err, result, fields) {
if (err) throw err;
if (result == "") {
console.log("no such user");
var loginStatus = {'uid': userid, 'isMember': false};
clients[id].sendUTF(JSON.stringify(loginStatus));
return;
} else if (userid == result[0].userid) {
console.log("successfull login");
var loginStatus = {'uid': userid, 'isMember': true};
users[id]=userid;
console.log("Users ID: "+users[id]+" ID:"+id);
clients[id].sendUTF(JSON.stringify(loginStatus));
//UPDATE USER AS ONLINE IN DB
con.query("UPDATE user_table SET isonline ='1' WHERE userid='" + userid + "'", function (err, result) {
if (err) throw err;
});
//UPDATE USER AS ONLINE IN DB
}
});
}else if(to=='chat'){
var msg = parsedMsg.msg;
for (var i in clients){
var chatLog = {'msg':msg,'user_id':users[id-1]};
clients[i].sendUTF(JSON.stringify(chatLog));
}
}else if(to=='register'){
console.log("register page");
}else if(to=='logout'){
delete clients[id];
console.log((new Date())+connection.remoteAddress+"is disconnected");
}
});
});
});
Это index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#frame-div{
border: lightgray solid 1px;
border-radius: 3px;
width: 40%;
margin: auto;
}
body{
font-family: Calibri;
}
.label{
display: table-cell;
padding-top: 15px;
padding-bottom: 5px;
}
.table{
display: table;
}
.table-row{
display: table-row;
}
</style>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
var wsUri ="ws://127.0.0.1:1337";
function init() {
websocket = new WebSocket(wsUri);
websocket.onopen = function (event) {
//
};
websocket.onmessage = function (event) {
var content = document.getElementById("content");
console.log("\n"+event.data);
var parsedContent = JSON.parse(event.data);
var uid = parsedContent.uid;
var isMember = parsedContent.isMember;
console.log(isMember);
if (isMember){
content.innerHTML="Welcome, "+uid+"<br>";
window.location.href='chat.html';
}
else if(!isMember) {
content.innerHTML+="Incorrect username / password!"+"<br>";
}
}
}
window.addEventListener("load",init,false);
function Login() {
var uid = document.getElementById("user-id").value;
var pass = document.getElementById("password").value;
websocket.send(JSON.stringify({'to':'login','uid':uid,'pass':pass}));
}
</script>
<div id="frame-div" class="table">
<div class="table-row">
<div class="label">Kullanıcı Adı:</div>
<div class="label"><input id="user-id" type="text"></div>
</div>
<div class="table-row">
<div class="label">Parola:</div>
<div class="label"><input id="password" type="password"></div>
</div>
<div class="table-row">
<div class="label">
<input type="button" value="Giriş Yap" onclick="Login()">
<form action="registration.html" style="display: inline-block">
<input type="submit" value="Üye Ol">
</form></div>
</div>
</div>
<p id="content"></p>
</body>
</html>
Это мой chat.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
font-family: Calibri;
}
#main-frame{
border: lightgray solid 0.5px;
border-radius: 10px;
background-color: burlywood;
padding: 10px;
width: 100%;
}
#left{
border: lightgray solid 1px;
border-radius: 10px;
background-color: white;
width: 80%;
margin: auto;
display: inline-block;
height: 350px;
}
#right{
border: lightgray solid 1px;
border-radius: 10px;
background-color: white;
width: 15%;
margin: auto;
display: inline-block;
height: 350px;
}
#bottom{
padding-top: 20px;
}
#inp{
width: 350px;
height: 30px;
border-radius: 5px;
}
#btn{
width: 100px;
height: 40px;
border-radius: 5px;
}
</style>
</head>
<script language="javascript" type="text/javascript">
var wsUri = "ws://127.0.0.1:1337/";
var output;
function init() {
output=document.getElementById("output");
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt) {
output.innerHTML ="Connected";
};
websocket.onmessage = function (event) {
var content = document.getElementById("chat-content");
var parsedContent = JSON.parse(event.data);
var user_id = parsedContent.user_id;
var msg = parsedContent.msg;
content.innerHTML+=user_id+" : "+msg+"<br/>";
}
}
window.addEventListener("load",init,false);
function sendMessage() {
var textsend = document.getElementById("inp").value;
websocket.send(JSON.stringify({'to':'chat','msg':textsend}));
}
function logout() {
websocket.send(JSON.stringify({'to':'logout'}));
window.location.href='index.html';
}
</script>
<body>
<div id="main-frame">
<div id="left">
Chat Main Screen:
<p id="chat-content"></p>
</div>
<div id="right">
Online Users:
</div>
<div id="bottom"><div><input type="text" id="inp"> <input type="button" value="Gönder" id="btn" onclick="sendMessage()"> <input
type="button" value="Çıkış Yap" onclick="logout()" style="float: right; width: 90px; height: 40px;
border-radius: 3px; margin-right: 30px"> </div></div>
</div>
<div id="output"></div>
</body>
</html>