简体   繁体   English

node.js中的response.end导致连接丢失

[英]Connection lost with response.end in node.js

I'm using node.js to have multiple clients. 我正在使用node.js来拥有多个客户端。 Now, in my code, I'm listening on a port and each time a client connects, I want to send out a broadcast message to all other clients, say. 现在,在我的代码中,我正在侦听端口,并且每次客户端连接时,我都想向所有其他客户端发送广播消息。 I'm raising a new event each time some new client connects, and I'm sending a response over to him. 每当有新客户连接时,我都会发起一个新事件,并向他发送回复。 When I say response.end(), I'm not able to send anything to that specific client after that. 当我说response.end()时,之后我无法将任何内容发送到该特定客户端。 However, the browser keeps loading and waiting for the response.end. 但是,浏览器会继续加载并等待response.end。 Is there anyway around this without using socket.io? 是否使用socket.io 就能解决此问题? I know socket.io has its uses, but I really wanted to know if I can do it without socket.io. 我知道socket.io有它的用途,但是我真的很想知道是否可以在没有socket.io的情况下使用它。

I'd say to use two channels in your client; 我想在您的客户中使用两个渠道; one to receive updates (channel kept open, or frequently querying for updates) and one to refresh the data. 一种用于接收更新(通道保持打开状态,或经常查询更新),另一种用于刷新数据。 It involves some work on your part to restructure the client and the server, but I think using two channels is the cleanest way to solve your problem. 它需要您进行一些工作来重组客户端和服务器,但是我认为使用两个渠道是解决问题的最干净的方法。

If you don't send the .end() the browser will keep waiting. 如果不发送.end(),浏览器将继续等待。 But if you close the channel you'll not be able to send nothing through it. 但是,如果您关闭该频道,则将无法通过该频道发送任何内容。 So, either use socket.io or open a channel via XHR and keep it open for each client to receive messages. 因此,可以使用socket.io或通过XHR打开一个通道,并保持打开状态以供每个客户端接收消息。 Is up to you to adequately frame the messages (implement your applicative protocolo) though. 不过,您可以自行决定是否适当构造消息(实施您的应用协议)。 I think Paul is right. 我认为保罗是对的。

Try long polling, which means letting an ajax request from the browser 'hang' until the server can send something back. 尝试长时间轮询,这意味着让浏览器发出的ajax请求“挂起”,直到服务器可以将某些内容发送回去。

How do I implement basic "Long Polling"? 如何实施基本的“长轮询”?

Using nodejs, you could store the response objects for the clients easily. 使用nodejs,您可以轻松存储客户端的响应对象。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM