为什么我的websocket服务器没有正确地提供我的HTML页面?

我在一个名为app.js的文件中使用NodeJS创build了一个web套接字的实例,并在端口8080上声明了一个监听器。但是,当我运行命令启动连接时,连接没有build立,也没有logging到控制台。 我试图打开一个Web套接字连接并创build一个谈话服务器。 当我运行我的app.js的createServer()函数不会触发和“新连接”不被logging。 有更多的参数,我需要打开连接? 我是websockets的新手; 任何帮助表示赞赏。

这是我的app.js代码:

var ws = require("nodejs-websocket") console.log("testing") var server = ws.createServer(function (conn) { console.log("New connection") conn.on("text", function (str) { console.log("Received "+str) conn.sendText(str.toUpperCase()+"!!!") }) conn.on("close", function (code, reason) { console.log("Connection closed") }) }).listen(8080); 

这里是我尝试连接到客户端网站的websocket。 我想发送websocket,不pipeinput到文本框中,然后在input标签中logging返回的string。

 <html> <body> <p> Result: <output type=text id="result0" value="" readonly></output> </p> <input type="text" onchange="connection.send(this.value); " /> <script> var connection = new WebSocket("ws://localhost:8080/echo"); connection.onmessage = function (event){ document.getElementById("result0").value = event.data; }; </script> </body> </html> 

它工作正常…在terminalA中执行你的服务器

 npm install -g nodejs-websocket # if not installed node my_websocket.js 

然后将您的客户端保存为文件browser_client.html,然后在相同的目录中发布这个启动一个新的terminalB中的httpd服务器

 npm install -g http-server # install an httpd server to render html file http-server -c-1 -p 8888 # this launches the httpd 

然后打开浏览器并指向链接

 http://localhost:8888/browser_client.html 

你会看到terminalA的输出

 New connection 

然后在浏览器的文本框中input一些文字

 apples and oranges 

这将出现在terminalA以及浏览器中