在我的node.js / Express.js应用程序中,我需要通过socket.io连接传递参数(请参见另一篇文章)。
在客户端,我有类似的东西:
编辑
var socket = io.connect('/image/change', {query:"name=my_img_name"}); var siofu = new SocketIOFileUpload(socket); siofu.listenOnInput(document.getElementById("change_image_inpt"));
在服务器端:
io.of('/image/change') .on('connection', function (socket) { console.log('log input param : ' + socket.handshake.query.name); });
但是控制台中什么也没有。
还有另一种方法可以实现吗?
编辑2
这是客户端的完整代码:
$(document).ready(function() { // icon_action_modal $('.icon_actions').on('click', function() { // set icon preview $('#icon_action_modal_icon_preview').html('<img src="/upload/icon/' + $(this).data('icon') + '.png" />'); // set icon to delete $('#icon_name').val($(this).data('icon')); // set Change icon socket var socket = io.connect('/icon_sets/change', {query:"name=my_img_name"}); var siofu = new SocketIOFileUpload(socket); siofu.listenOnInput(document.getElementById("change_icon")); // Do something when a file is uploaded siofu.addEventListener("complete", function () { $('.overlay').hide(); }); // display loader window socket.on('displayOverlay', displayOverlay); // display socket.on('displayIconImage', function (data) { $('#iconset_render').append('<div class="icon"><img src="' + data.path + '" /></div>'); }); socket.on('setIconsetArray', function (data) { var iconset = ($('#iconset_array').val()) ? JSON.parse($('#iconset_array').val()) : []; iconset.push(data.iconName); $('#iconset_array').val(JSON.stringify(iconset)); deleteIcon($('#icon_name').val()); // close modal $('#icon_action_modal').modal('hide'); }); }); $('#icon_action_modal_delete_icon').on('click', function() { deleteIcon($('#icon_name').val()); // close modal $('#icon_action_modal').modal('hide'); }); }); // end document.ready
以及服务器端的完整代码:
io.of('/icon_sets/change') .on('connection', function (socket) { console.log('log input param : ' + socket.handshake.query.name); functions.socketImageTransfer(socket, 'icon', 65, 65); });
具有socketImageTransfer功能:
socketImageTransfer
module.exports.socketImageTransfer = function(socket, type, width, height, name) { var socketioFileUploadServer = require('socketio-file-upload'); // upload files by socket var config = require(__dirname + '/config/config.json'); var easyimg = require('easyimage'); // crop - resize image var fs = require('fs'); // file system access // Make an instance of socketioFileUploadServer and listen on this socket: var uploader = new socketioFileUploadServer(); uploader.dir = config.tmpDir; uploader.listen(socket); // Do something when a file is saved: uploader.on('saved', function (event) { console.log('Original ' + type + ' saved'); // resize and rename image with a unique id var newName; if (!name) { newName = Math.random().toString(36).substr(2, 9) + '_' + type + '.png'; } else { newName = name; } var fileName = event.file.name.replace(/ /g, '_'); easyimg.rescrop({src: config.tmpDir + fileName, dst: config.uploadDir + type + '/' + newName, width: width, height: height}, function (err, image) { if (err) return console.log(err); console.log(type + ' resized and cropped: ' + image.width + ' x ' + image.height); // image is uploaded - resized - croped, now display it socket.emit('display' + ucfirst(type) + 'Image', {path: '/upload/'+ type + '/' + newName}); // remove original from file system fs.unlink(config.tmpDir + fileName, function () { if (err) throw err; console.log('Original ' + type + ' removed'); }); // additionnal action switch(type) { case 'icon': // send path to generate iconset_json socket.emit('setIconsetArray', {iconName: newName}); break; } }); }); uploader.on('start', function (event) { console.log('Client start upload'); socket.emit('displayOverlay'); }); // Error handler: uploader.on('error', function (event) { console.log("Error from uploader", event); }); };
感谢你的帮助
就在这里。
1)query就像GET参数一样,因此请替换"param:value"为"param=value"(如果您想传递多个参数,请像通常使用URL:一样进行操作param=value&some_other_param=test)
query
GET
"param:value"
"param=value"
param=value&some_other_param=test
2)handshaken在connection处理程序中获取查询参数有一种更简单,更可靠的方法(因为没有访问对象的未定义属性的风险):
handshaken
connection
console.log(socket.handshake.query.param);
编辑:
学习完完整的代码后,我想我找出了导致问题的原因。问题是您可能误解了Socket.IO名称空间的主要思想。
我猜您io.connect在一页内有多个Socket.IO连接(调用),对吗?通常,一个连接就足够了。您的错误是您调用io.connect了鼠标事件,但是您应该在上调用一次document.ready,然后才发出emit声音。
io.connect
document.ready
emit
看下面的代码(客户端):
$(document).ready(function() { var socket = io.connect('', {query: 'name=something'}); // [...] socket.on('some_event_from_server', function(data, cb) {}); // [...] $('#someButton').click(function() { socket.emit('markers_add', {some: 'data'}); //send `markers_add` message to server within main namespace }); $('#someOtherButton').click(function() { socket.emit('icon_sets_add', {some: 'thing'}, function(response) { //server may response to this request. see server side code below }); }); });
服务器端代码:
io.on('connection', function(socket) { //connection handler of main namespace socket.on('markers_add', function(data) { /* ... */ }); socket.on('icon_sets_add', function(data, cb) { // do something cb({some: 'response'}); }); // [...] socket.emit('some_event_from_server', {}); //server sends a message to a client //BTW, now it should be OK: console.log(socket.handshake.query.name); });
如果您有一个名称空间,它应该可以工作。我实际上不知道这是Socket.IO的错误还是名称空间使用不当的结果,但是修改代码以仅创建一个名称空间应该可以解决问题。 因此,就您而言,您根本不必在握手时传递查询参数。 实际上,如果要使您的应用程序更安全,则必须使用查询参数。请参阅http://wlkns.co/node-js/socket-io- authentication-tutorial-server-and-client/(对于Socket.io 0.9)
希望我的回答对您有所帮助。祝好运!