Node.js 通过socket.io向连接到nodejs服务器的所有客户端广播更新的数据
我正在编写一个应用程序,每当一个客户端通过ajax请求连接到本地套接字服务器并更新系统时,它都需要能够更新所有连接的客户端。处理请求很好,但将响应从本地套接字服务器发送到socket.io以向所有人广播是我遇到问题的地方。我确信我在这里看到的是一些简单的东西,但这对我来说是非常新的,所以我遇到了一些问题,特别是异步编程的思维方式。下面是一个简短的版本,我正试图完成和我的步履蹒跚Node.js 通过socket.io向连接到nodejs服务器的所有客户端广播更新的数据,node.js,express,socket.io,Node.js,Express,Socket.io,我正在编写一个应用程序,每当一个客户端通过ajax请求连接到本地套接字服务器并更新系统时,它都需要能够更新所有连接的客户端。处理请求很好,但将响应从本地套接字服务器发送到socket.io以向所有人广播是我遇到问题的地方。我确信我在这里看到的是一些简单的东西,但这对我来说是非常新的,所以我遇到了一些问题,特别是异步编程的思维方式。下面是一个简短的版本,我正试图完成和我的步履蹒跚 var express = require('express'), http = require('ht
var express = require('express'),
http = require('http'),
net = require('net'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.get("/execute", function (req, res) {
// connect to local socket server
var localSock = net.createConnection("10000","127.0.0.1");
localSock.setEncoding('utf8');
localSock.on('data', function(data) {
// send returned results from local socket server to all clients
do stuff here to data ...
send data to all connected clients view socketio socket...
var dataToSend = data;
localSock.end();
}).on('connect', function(data) {
// send GET data to local socket server to execute
var command = req.query["command"];
localSock.write(command);
});
app.get (..., function() {});
app.get (..., function() {});
server.listen('3000');
io.on('connection', function(client) {
client.broadcast.send(dataToSend);
});
下面是来自一个非常流行的网站的一些代码。为了使用Express3.x,进行了一些更改 以下是app.js的代码:
var express = require('express')
, http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// usernames which are currently connected to the chat
var usernames = {};
io.sockets.on('connection', function (socket) {
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});
obove代码与webtutorial中的代码相同,只是使用了对express3.x进行了一些更改
以下是index.html的代码:
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:8000');
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
$('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
});
// listener, whenever the server emits 'updateusers', this updates the username list
socket.on('updateusers', function(data) {
$('#users').empty();
$.each(data, function(key, value) {
$('#users').append('<div>' + key + '</div>');
});
});
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>USERS</b>
<div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;" />
<input type="button" id="datasend" value="send" />
</div>
var socket=io.connect('http://localhost:8000');
//在连接到服务器时,通过匿名回调请求用户名
socket.on('connect',function(){
//调用服务器端函数“adduser”并发送一个参数(prompt的值)
emit('adduser',prompt(“你叫什么名字?”);
});
//侦听器,无论何时服务器发出“updatechat”,都会更新聊天主体
socket.on('updatechat',函数(用户名、数据){
$(“#对话”).append(“+username+”:“+data+”
”);
});
//侦听器,每当服务器发出“updateusers”时,就会更新用户名列表
socket.on('updateusers',函数(数据){
$('#users').empty();
$。每个(数据、函数(键、值){
$(“#用户”).append(“”+key+“”);
});
});
//加载页面
$(函数(){
//当客户端单击SEND时
$('#datasend')。单击(函数(){
var message=$('#data').val();
$('数据').val('');
//告诉服务器执行“sendchat”并发送一个参数
发出('sendchat',消息);
});
//当客户端在键盘上按ENTER键时
$(“#数据”)。按键(功能(e){
如果(e.which==13){
$(this.blur();
$('#datasend')。焦点()。单击();
}
});
});
使用者
以下是一些来自一个非常流行的网站的代码。为了使用Express3.x,进行了一些更改
以下是app.js的代码:
var express = require('express')
, http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// usernames which are currently connected to the chat
var usernames = {};
io.sockets.on('connection', function (socket) {
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});
obove代码与webtutorial中的代码相同,只是使用了对express3.x进行了一些更改
以下是index.html的代码:
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:8000');
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
$('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
});
// listener, whenever the server emits 'updateusers', this updates the username list
socket.on('updateusers', function(data) {
$('#users').empty();
$.each(data, function(key, value) {
$('#users').append('<div>' + key + '</div>');
});
});
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>USERS</b>
<div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;" />
<input type="button" id="datasend" value="send" />
</div>
var socket=io.connect('http://localhost:8000');
//在连接到服务器时,通过匿名回调请求用户名
socket.on('connect',function(){
//调用服务器端函数“adduser”并发送一个参数(prompt的值)
emit('adduser',prompt(“你叫什么名字?”);
});
//侦听器,无论何时服务器发出“updatechat”,都会更新聊天主体
socket.on('updatechat',函数(用户名、数据){
$(“#对话”).append(“+username+”:“+data+”
”);
});
//侦听器,每当服务器发出“updateusers”时,就会更新用户名列表
socket.on('updateusers',函数(数据){
$('#users').empty();
$。每个(数据、函数(键、值){
$(“#用户”).append(“”+key+“”);
});
});
//加载页面
$(函数(){
//当客户端单击SEND时
$('#datasend')。单击(函数(){
var message=$('#data').val();
$('数据').val('');
//告诉服务器执行“sendchat”并发送一个参数
发出('sendchat',消息);
});
//当客户端在键盘上按ENTER键时
$(“#数据”)。按键(功能(e){
如果(e.which==13){
$(this.blur();
$('#datasend')。焦点()。单击();
}
});
});
使用者
全局套接字对象被引用为io.sockets
。因此,要进行全局广播,只需将数据传递到io.sockets.emit()
,它将被发送到所有客户端,而不管名称空间如何
您发布的代码,假设您的意思是io.sockets.on
:
io.on('connection', function(client) {
client.broadcast.send(dataToSend);
});
正在侦听到任何命名空间的任何连接,并在建立连接后向所有客户端广播dataToSend
。因为您的主要目标是向每个人发送数据,所以您只需要利用全局名称空间,io.sockets
,但它在代码中的使用方式不起作用
app.get('/execute', function (req, res) {
var localSock = net.createConnection("10000","127.0.0.1");
localSock.setEncoding('utf8');
localSock.on('connect', function(data) {
var command = req.query.command;
localSock.write(command);
});
localSock.on('data', function(data) {
var dataToSend = data;
localSock.end();
});
});
在代码的这一部分中,您正在正确地侦听路径/execute
上的GET
请求,但套接字逻辑不正确。您在连接时立即编写命令
,这很好,但您假设数据
事件意味着数据流已经结束。由于流具有事件end
,因此您希望使用data
事件收集响应,然后最后对end
上的数据执行一些操作
例如,如果服务器发送了字符串,这是一个正在传输的字符串。
,您将使用:
localSock.on('data', function(data) {
var dataToSend = data;
localSock.end();
});
您可能只会收到这是一个stri
,然后使用end()
提前关闭套接字。相反,您希望执行以下操作:
var dataToSend = [];
localSock.on('data', function(data) {
dataToSend.push(data);
});
localSock.on('end', function() {
dataToSend = dataToSend.join('');
io.sockets.emit(dataToSend);
});
注意,在这种情况下,您不需要使用end()
,因为删除服务器将发送自己的FIN
数据包
我想问一下你在用net.Socket
做什么,因为返回的数据是a,这意味着,当你监听data
事件时,数据可能是完整响应的片段,在end
事件触发之前必须收集这些片段