socket.io 使用方式 单独使用 依附http模块区别
发布于 9 年前 作者 lik0914 6179 次浏览 最后一次编辑是 8 年前 来自 问答

看socket. github资料说 The following example attaches socket.io to a plain Node.JS HTTP server listening on port 3000.

var server = require(‘http’).createServer(); var io = require(‘socket.io’)(server); io.on(‘connection’, function(socket){ socket.on(‘event’, function(data){}); socket.on(‘disconnect’, function(){}); }); server.listen(3000); Standalone

var io = require(‘socket.io’)(); io.on(‘connection’, function(socket){}); io.listen(3000); In conjunction with Express

Starting with 3.0, express applications have become request handler functions that you pass to http or http Server instances. You need to pass the Server to socket.io, and not the express application function.

var app = require(‘express’)(); var server = require(‘http’).createServer(app); var io = require(‘socket.io’)(server); io.on(‘connection’, function(){ /* … */ }); server.listen(3000);

这几种使用方式, 他们有什么区别呢

3 回复

虽然是不同的使用方式,但最终socket io都是使用http模块创建的server.

@hiearth 性能上, 有什么差异吗?

没什么差别,看你如何用socket.io模块 在express之上开发的可以用第三种,其他可以选择前两种

回到顶部