为什么 web socket 在 nodejs 上表现不同? [英] why web socket behave differently on nodejs ?

查看:37
本文介绍了为什么 web socket 在 nodejs 上表现不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Nodejs Server.js 代码:

I have a Nodejs Server.js code :

第一个概念:

var http = require('http');
var express = require('express');
var app = express();
var path = require('path');

var conn= http.createServer(app).listen(3000, function () {
  console.log("server Running at Port 3000");
});

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({server: conn});

我有一个带有java脚本的index.html代码:

and i have a index.html code with java script :

<html>
<body> 

<script src="myscript.js"></script>

</body>
</html>

myscript.js 里面我有:

var connection = new WebSocket('ws://localhost:3000');

当我在浏览器上打开 http://localhost:3000 时,这工作正常.

This is working fine when i open http://localhost:3000 on browser .

第二个概念:

我的 server.js :

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 3000}) ;

wss.on('connection', function (connection) {

});

wss.on('listening', function () {
    console.log("Server started...");
});

和 HTML 和客户端 java 脚本与上面类似.

and HTML and client java script is similar as above .

当我在浏览器上打开 http://localhost:3000 时,这不起作用.为什么 ?我想澄清我的疑问.为什么第一种方法有效而第二种方法无效?

This is not working when i open http://localhost:3000 on browser . why ? i want to clarify my doubt . Why the first method working and second is not working ?

推荐答案

专门回答你的问题:为什么 web socket 在 nodejs 上表现不同? 答案是:不应该.在您的代码的第二个版本中,您不会在端口 3000 上向客户端提供任何 HTML 或 JS 文件,因此浏览器无法下载任何 HTML.

To specifically answer your question: why web socket behave differently on nodejs? the answer is: It shouldn't. In the second version of your code you are not serving any HTML or JS files to the client on the port 3000 so the browser can't download any HTML.

如果您希望它按预期工作,那么您需要向访问 http:/的浏览器提供一些 HTML 和 JS 文件/localhost:3000/ 否则将无法连接.

If you want it to work as expected then you need to serve some HTML and JS files to the browser that visits http://localhost:3000/ or otherwise it will not be able to connect.

我写了一些示例代码——服务器端和客户端——关于如何使用 WebSocket 来完成你在这里想要做的事情.可在 GitHub 上使用,我最初是为这个答案写的:socket.io 和 websockets 之间的区别.

I wrote some example code - both server-side and client-side - on how to use WebSocket to do exactly what you are trying to do here. It's available on GitHub and I originally wrote it for this answer: Differences between socket.io and websockets.

此处针对您的问题的源代码的相关部分是:

The relevant parts of the source code for your question here are:

使用 Express.js 的 WebSocket 服务器示例:

WebSocket server example using Express.js:

var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
  console.error('websocket connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');

来源:https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js

使用原生 JavaScript 的 WebSocket 客户端示例:

WebSocket client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });

来源:https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html

与其调试不工作的代码,有时最好从有效的东西开始,然后从那里开始.看看它是如何工作的,可以随意更改它并在您的项目中使用它 - 它在 MIT 许可证.

Instead of debugging a code that it not working, sometimes it's better to start from something that works and go from there. Take a look at how it all works and feel free to change it and use it in your projects - it's released under MIT license.

这篇关于为什么 web socket 在 nodejs 上表现不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆