Why did I failed to connect to websocket?

最后都变了- 提交于 2019-12-11 18:07:43

问题


The code of Node server with ws module:

show = console.log

WS = require('ws').Server
wss = new WS port: 8080
wss.on 'connection', (ws) ->
  show 'a connection'
  ws.on 'message', (message) ->
    show 'received: %s', message
  ws.send 'something'

I can connect to websocket by running the code below on the same server, and it gives out "a connection":

WS = require 'ws'
ws = new WS 'ws://localhost:8080'

But when I run these lines of code from browser, there's no respose:

s = new WebSocket('ws://184.82.253.196:8080');
s.send('nothing');

What's problem, how can I fix it?


回答1:


Websocket server start listening only 127.0.0.1 by default. Use this code to start listen all interfaces.

show = console.log

WS = require('ws').Server
wss = new WS port: 8080, host: '0.0.0.0'
wss.on 'connection', (ws) ->
  show 'a connection'
  ws.on 'message', (message) ->
    show 'received: %s', message
  ws.send 'something'


来源:https://stackoverflow.com/questions/12083966/why-did-i-failed-to-connect-to-websocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!