我是NodeJs的新手。现在我正在尝试socket.io。我想建立像Zopim(https://www.zopim.com/)这样的网站。现在我正在努力:客户端(A)应该只从一个管理员获取帮助热线,并防止其他管理员与客户端(A)聊天。 这是server.js
var app = require('express')();
var bodyParser = require('body-parser');
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(require("express").static('data'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
/* Creating MySQL connection.*/
var con = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database :'Chat_tryout'
});
var insertRecord = 'Insert into mytable(socketid,receiver,message)value(?,?,?)';
app.get("/",function(req,res){
res.sendFile(__dirname + '/index.html');
});
var msg={};
io.on('connection', function(socket){
console.log(socket.id + "connected");
socket.on('message',function(msg){
console.log('user' +this.id+ 'sent message"'+ msg +'"');
//console.log(" admin id " + io.sockets.connected[socketid]);
con.getConnection(function(err, connection) {
var message=msg;
var socketid=" ";
con.query( insertRecord,[socketid,socket.id,msg], function(err, res) {
if(err){
console.log("error:" + err);
}else
console.log ("inserted"+ socket.id +"message"+ msg);
//res.end(``);
});
});
app.post('/get_data', function (req, res) {
var msg=req.body.name;
var toid = req.body.toid;
//var socketid = this.socket.sessionid;
//console.log(socketid);
console.log(toid);
io.to(toid).emit('mymessage',msg);
con.getConnection(function(err,connection){
var message=msg;
con.query( insertRecord,[socketid,toid,msg], function(err, res) {
if(err){
console.log("error:" + err);
}else
console.log ( "inserted "+ socket.id +" message "+ msg);
});
});
});
});
socket.on('disconnect', function() {
console.log('client socketio disconnect!');
});
app.get('/api/getalldata', function(req,res){
con.getConnection(function(err,connection){
con.query( 'select * from mytable', function(err, rows) {
if(err){
console.log("error:" + err);
}else
console.log ("success");
res.json(rows);
});
});
});
});
http.listen(8080,function(){
console.log("Listening on http://127.0.0.1:8080/");
});
Index.html: (管理员页面)
<html ng-app="sample">
<head>
<title>Connecting Node.js app to MySql</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script type="text/javascript">
var app = angular.module('sample',[]);
app.controller('sample', function ($scope,$http,$timeout) {
$scope.data_server={};
$scope.socketid={};
var TypeTimer;
var TypingInterval = 1000;
$scope.keyup = function() {
$timeout.cancel(TypeTimer);
TypeTimer=$timeout( function(){ get_data(); }, TypingInterval);
};
$scope.keydown = function(){
$timeout.cancel(TypeTimer);
};
function get_data(){
var name=$scope.name;
var toid = $scope.toid;
$http.post('/get_data',{name:name,toid:toid}).success(function(data, status, headers, config) {
// $scope.data_server=data;
}).error(function(data, status) {
//alert("Connection Error");
});
}
$scope.getalldata = function(){
$http.get('/api/getalldata')
.success(function(data) {
$scope.data_server = data;
// console.log(data);
})
.error(function(err) {
console.log('Error: ' + err);
});
};
});
</script>
</head>
<body ng-controller="sample">
<div class="container">
<div id="name-group" class="form-group">
<h2>ADMIN</h2>
<ul id="messages"></ul>
<br/>
<input type="text" class="form-control" ng-model="name" placeholder="Type here and check the Title in Tab"/>
<input type="text" class="form-control" ng-model="toid" ng-keyup="keyup()" ng-keydown="keydown()" ng-blur="blur()" ng-change="change()"/>
{{toid}}
<br/>
</div>
<div class="table-responsive">
<table class="table table-hover"ng-repeat="data in data_server" >
<thead>
<tr>
<th>From</th>
<th>Message</th>
</thead>
<tbody>
<tr>
<td>{{data.receiver}}</td>
<td>{{data.message}}</td>
<!-- <td><input type="text" value="{{data.receiver}}"><td>
<td><input type="text" ng-model="reply" ng-keyup="submit()"></td>-->
</tr>
</tbody>
</table>
</div>
<div class="rows">
<div class="col-md-12">
<div class="data" >
<!---{{ data_server}}--->
<hr/>
</div>
<div ng-show="data_server.length == 0" >
<div class="alert alert-info" >
<p class="text-center" >
Sorry, Right now we don't have any results for you.
</p >
</div >
</div >
</div>
</div>
<div class="rows">
<button class="btn btn primary" ng-click="getalldata()">Get Messages</button>
<div class="form-row form-last-row">
</div>
</div>
</div>
</body>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io.connect("http://localhost:8080");
socket.on('message', function(msg){
$('#messages').append($('<li>').text(msg));
});
我正在使用html前端为客户端发送和接收消息:
var socket = io.connect("http://localhost:8080");
$('form').submit(function(){
socket.emit('message', $('#message').val());
$('#message').val('');
return false;
});
socket.on('mymessage', function(msg){
$('#messages').append($('<li>').text(msg));
});