为什么 websocket 只能以 localhost 成功连接?
我在一台盛大云 VPS 上跑了个 ws 模块的 websocket,
然后 VPS 的端口是打开的,
大致代码是:
WebSocketServer = require('ws').Server
wss = new WebSocketServer port: 8071
wss.on 'connection', (ws) ->
show 'connection'
record = time
me = repeat 1000, ->
if time isnt record
delay 100, -> ws.send 'reload'
ws.on 'close', ->
clearInterval me
show 'close'
然后从浏览器访问, 没有看到 connection 打印出来, 应该是连接失败,
s = new WebSocket('ws://172.17.15.63:8071')
然后我从 VPS 上用下面的代码访问, 连接成功打印了 connection,
WS = require 'ws'
ws = new WS 'ws://localhost:8071'
ws.on 'open', ->
ws.send 'something'
ws.on 'message', (message) ->
console.log 'got %s', mseeage
我在局域网的两台电脑上相互访问也是这样的情况, 这是为什么呢?
2 回复
ws 默认监听 127.0.0.1 而不是 0.0.0.0 的说, 要改参数, 然后 OK 了
http://stackoverflow.com/questions/12083966/why-did-i-failed-to-connect-to-websocket