编辑1:
好的,服务器问题解决了。这是集成到我的项目中的完整服务器代码。
var http = require('http');
var express = require('express');
var requestHandler = require(__dirname + '/app_modules/request-handler.js');
var app = express();
app.configure(function(){
app.use(express.static(__dirname + '/html'));
app.use(express.bodyParser());
});
var httpServer = http.createServer(app);
httpServer.listen(80);
var io = require('socket.io').listen(httpServer);
io.on('connection', function(socket){
socket.on('event', function(data){
});
socket.on('disconnect', function(){
});
});
下一个问题是在我的静态html页面中包含源.js。这会引发错误:
<script src="/socket.io/socket.io"></script>
Resource interpreted as Script but transferred with MIME type text/plain: "http://localhost/socket.io/socket.io". localhost/:206
Uncaught SyntaxError: Unexpected identifier socket.io:1
Uncaught ReferenceError: io is not defined
原始问题:
我正试图让这个吸盘在测试服务器上工作。这是1:1,直接来自github上的socket.io文档。
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('event', function(data){
});
socket.on('disconnect', function(){
});
});
server.listen(3000);
这是我得到的:
[INFO] 19:37:40 Restarting
[ERROR] 19:37:40 TypeError
TypeError: object is not a function
at Object.<anonymous> (/Users/me/work/github/node-forever-gui/server/socket_test.js:3:30)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Object..js (/usr/local/lib/node_modules/node-dev/lib/hook.js:52:17)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/usr/local/lib/node_modules/node-dev/lib/wrap.js:47:1)
at Module._compile (module.js:456:26)
所有模块均通过 npm 安装。请帮我解决这个问题!
答案 0 :(得分:9)
正如所述,io
不是函数,您无法将HTTP对象传递给它。请使用listen方法将Socket.IO附加到HTTP实例。
var io = require('socket.io').listen(server);
对于第二个错误,该文件是一个脚本,并具有扩展名。将.js
添加到参考。
<script src="/socket.io/socket.io.js"></script>
答案 1 :(得分:0)
有些人有此问题,因为es6 env中的导入被写错了
我的代码出现错误时
2.6637108 # Set-Content
5.1850954 # Out-File; took almost twice as long.
UnhandledPromiseRejectionWarning:TypeError:socket_io_1.socketIo不是函数
修复很简单
import { socketIo } from 'socket.io';
// start server on port
const server = app.server.listen(process.env.PORT || config.port, () => {
console.log(` ====== Listening on ${app.server.address().port} ====== `.bgWhite.black.bold);
});
// socketIo.io
const io = socketIo(server);
io.on('connection', (socket) => {
console.log(` ====== Socket Connected => `.bgWhite.black.bold, socket.id);
});
这是一个示例https://github.com/luixaviles/socket-io-typescript-chat/blob/master/server/src/chat-server.ts