简体   繁体   English

如何在同一台服务器上同时发出 HTTP 和 Websocket 请求?

[英]How can I make both HTTP and Websocket requests at the same time on the same server?

I am trying to run a server doing HTTP and Websocket requests.我正在尝试运行执行 HTTP 和 Websocket 请求的服务器。 The HTTP requests will be used to pull data from a local file called “geo-data.json”, which I need to show a map of NYC using D3.js and the topojson library. HTTP 请求将用于从名为“geo-data.json”的本地文件中提取数据,我需要使用 D3.js 库和 topojson 库显示 NYC 的 map。

I am using Node.js to run the server.我正在使用 Node.js 来运行服务器。 My package.json file looks like this:我的 package.json 文件如下所示:

{
  "name": "inputusername_showlistofusers",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "node server.js"
 },
  "author": "",
  "license": "ISC",
  "dependencies": {
  "node-geocoder": "^3.27.0",
  "ws": "^7.3.0"
 }
}

My Websocket configuration on the client side looks like this:我在客户端的 Websocket 配置如下所示:

var wsUri = "ws://localhost:8080";
var ws = new WebSocket(wsUri);

ws.onopen = function (evt) {
    console.log("1. Connected (from Client)")
}

ws.onmessage = function (message) {
    var messageArray = JSON.parse(message.data)
    console.log("5. This is the list of user names:", messageArray)
}

Also, on the client side I am including my D3 code to read the geo data from the “geo-data.json” and the “nyc-streets.json” files by using D3.json:此外,在客户端,我包含了我的 D3 代码,以使用 D3.json 从“geo-data.json”和“nyc-streets.json”文件中读取地理数据:

d3.json('geo-data.json', function (error, data) {
//code
}

d3.json('nyc-streets.json', function (error, data) {
//code
}

On the server side, I am using Websockets to broadcast a message.在服务器端,我使用 Websockets 来广播消息。 The code looks like this:代码如下所示:

var WebSocket = require("ws");
wss = new WebSocket.Server({ port: 8080 });

wss.on("connection", function connection(ws) {  

    console.log("2. Connected (from Server)")

    ws.on("message", function incoming(message) {

        console.log("3. received from the client ", message);

        wss.clients.forEach(function each(client) {
            if (client.readyState === WebSocket.OPEN) {

                client.send(JSON.stringify(message));
                console.log("7. All names connected: ", message)
             }
        })
    })
})

The problem: when I run server.js using “node server.js”, the code (both on client and server) that requires Websocket runs smoothly, but the one that requires https does not:问题:当我使用“node server.js”运行 server.js 时,需要 Websocket 的代码(在客户端和服务器上)运行顺利,但需要 https 的代码运行平稳:

d3.json('geo-data.json', function (error, data)    

and I get the following error (I am opening the index.html file using File/Users…):我收到以下错误(我正在使用文件/用户打开 index.html 文件...):

Access to XMLHttpRequest at 'file:///Users..." from origin 'null' has been blocked by CORS CORS 已阻止从源“null”访问“file:///Users...”处的 XMLHttpRequest
policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.策略:跨域请求仅支持协议方案:http、data、chrome、chrome-extension、https。

So I tried to fix this using http-server to run the server and also by making the following change on package.json: “scripts”:{start: “index.html”} However, now the Websocket code does not work, and I get the following error:因此,我尝试使用 http-server 来运行服务器并通过对 package.json 进行以下更改来解决此问题:“scripts”:{start:“index.html”} 但是,现在 ZFEA54C8A1121D633BE6BFA9B5 代码不起作用,并且我收到以下错误:

(index):112 WebSocket connection to 'ws://localhost:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200 (索引):112 WebSocket 连接到“ws://localhost:8080/”失败:WebSocket 握手期间出错:意外响应代码:200

How can I make both HTTP and Websocket requests at the same time?如何同时发出 HTTP 和 Websocket 请求?

Thanks in advance.提前致谢。

Gonna post an overwhelming amount of info here and then I'll summarize at the end.将在这里发布大量信息,然后我将在最后进行总结。 Ultimately, Web Sockets is probably not the tool that you want to use.最终,Web Sockets 可能不是您想要使用的工具。 Likely, web sockets is working but it has a subtle difference from what you were expecting. web sockets 可能正在工作,但它与您的预期有细微差别。 Web Sockets are great for constant communication. Web Sockets 非常适合持续通信。 A messenger or chat is a great use for this as you will constantly be checking for new messages.信使或聊天对此很有用,因为您将不断检查新消息。

I suggest using express instead.我建议改用快递。 Here is a simple file that should get you started: https://www.tutorialsteacher.com/nodejs/serving-static-files-in-nodejs .这是一个可以帮助您入门的简单文件: https://www.tutorialsteacher.com/nodejs/serving-static-files-in-nodejs It serves all the files that are in a public folder.它为公共文件夹中的所有文件提供服务。 You may want to move your files into such a folder.您可能希望将文件移动到这样的文件夹中。

The big issue is that the function d3.json( does not connect to your sockets. It looks up the file locally (which is possible but ultimately results in the CORS security error). That function is responsible for retrieving data. If you called the correct url d3.json('localhost:8080/geo-data.json under the new Express app, then you should have success. You will not need to do anything for network connections on the client side (no websockets or express on your client) The big issue is that the function d3.json( does not connect to your sockets. It looks up the file locally (which is possible but ultimately results in the CORS security error). That function is responsible for retrieving data. If you called the在新的 Express 应用程序下正确的 url d3.json('localhost:8080/geo-data.json ,那么你应该成功了。你不需要对客户端的网络连接做任何事情(你的客户端上没有 websockets 或 express )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何同时使用道具和帖子? - How can I use both props and posts at the same time? 如何在同一服务器上处理TCP / IP原始请求和HTTP请求 - How to handle tcp/ip raw requests and http requests on the same server 同时发出2个Ajax请求? - Make 2 Ajax requests at the same time? 我想进行搜索,我可以同时搜索大写和小写..? - i want to make a search in which i can search upper case and lower case both at same time..? 如何减少HTTP请求? - How can I Make fewer HTTP requests? 运行在同一个 NodeJS 进程上的 http 服务器和 websocket 服务器可以在本地相互通信吗? - Can an http server and a websocket server running on the same NodeJS process communicate with each other locally? 提交按钮同时使用两种方法,而不是一种,我该如何解决? - Submit button uses both methods at the same time, instead of one, how can I fix this? EXT拖放事件发生冲突-即 如何同时使用ondragout和notifyout? - EXT drag and drop events clash - ie. how can I use both ondragout and notifyout at the same time? 检测同时向服务器调用多个请求 - Detect calling multi requests at same time to server 如何在同一节点服务器上同时呈现Jade模板和HTML文件? - How can I render both Jade templates and HTML files on same Node server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM