如何在节点中使用socket.io?

时间:2017-03-19 13:26:02

标签: javascript node.js sockets socket.io

我学习节点,我有socket.io的例子。

在package.json中我有:

{
  "name": "test",
  "version": "0.0.1",
  "description": "test",
  "dependencies": {
    "mime": "~1.2.7",
    "socket.io": "*"
  }
}

我做了:

npm install

我收到:

+-- mime@1.2.11
`-- socket.io@1.7.3
  +-- debug@2.3.3
  | `-- ms@0.7.2
  +-- engine.io@1.8.3
  | +-- accepts@1.3.3
  | | +-- mime-types@2.1.14
  | | | `-- mime-db@1.26.0
  | | `-- negotiator@0.6.1
  | +-- base64id@1.0.0
  | +-- cookie@0.3.1
  | +-- engine.io-parser@1.3.2
  | | +-- after@0.8.2
  | | +-- arraybuffer.slice@0.0.6
  | | +-- base64-arraybuffer@0.1.5
  | | +-- blob@0.0.4
  | | `-- wtf-8@1.0.0
  | `-- ws@1.1.2
  |   +-- options@0.0.6
  |   `-- ultron@1.0.2
  +-- has-binary@0.1.7
  | `-- isarray@0.0.1
  +-- object-assign@4.1.0
  +-- socket.io-adapter@0.5.0
  +-- socket.io-client@1.7.3
  | +-- backo2@1.0.2
  | +-- component-bind@1.0.0
  | +-- component-emitter@1.2.1
  | +-- engine.io-client@1.8.3
  | | +-- component-emitter@1.2.1
  | | +-- component-inherit@0.0.3
  | | +-- has-cors@1.1.0
  | | +-- parsejson@0.0.3
  | | +-- parseqs@0.0.5
  | | +-- xmlhttprequest-ssl@1.5.3
  | | `-- yeast@0.1.2
  | +-- indexof@0.0.1
  | +-- object-component@0.0.3
  | +-- parseuri@0.0.5
  | | `-- better-assert@1.0.2
  | |   `-- callsite@1.0.0
  | `-- to-array@0.1.4
  `-- socket.io-parser@2.3.1
    +-- component-emitter@1.1.2
    +-- debug@2.2.0
    | `-- ms@0.7.1
    `-- json3@3.3.2

所以没有错误。

在html中我使用(例如):

<script src='/socket.io/socket.io.js' type='text/javascript'></script>

但是在控制台中我有错误:

"NetworkError: 404 Not Found - http://localhost:3000/socket.io/socket.io.js"

在文件夹 node_modules 中,我有结构:

node_modules
--- socket.io
------ lib
--------- client.js
--------- index.js
--------- namespace.js
--------- socket.js

我也尝试了其他路径:

/socket.io/lib/socket.js /socket.io/socket.js

/socket.io/lib/index.js /socket.io/index.js

等...但我仍然有错误404.如何在html中将此项包含在我的项目中?

1 个答案:

答案 0 :(得分:-1)

你需要

compression.type

并使用

npm install --save-dev socket.io-client

或者,如果您在客户端上使用CommonJS或ES6,则可以通过

导入scoket.io
<script src="node_modules/socket.io-client/dist/socket.io.js"></script>

const io = require('socket.io-client')