如何与Socket.io连接一次?
我正在使用socket.io。它运作良好,但我对性能有一个短暂的怀疑。我不确定我是否很好地使用了连接。
这是我的客户端脚本(jade模板语言):
!!! 5
html
head
title Foo
script(type='text/javascript', src='/javascript/socket.io.min.js')
script(type='text/javascript')
socket = new io.Socket('localhost', 3000);
socket.connect();
socket.on('message', function(data) {
});
body
该脚本在每个页面上加载(因为它是我的布局页面)。因此,在每个页面上,套接字都会连接到服务器套接字。这是我的问题,我不喜欢这个想法。
是否可以为每个客户端页面将客户端套接字连接到服务器套接字一次?
此外,是否可以加载一次(每个客户端)/javascript/socket.io.min.js
库?
谢谢。
I'm using socket.io. It works well, but I have a short doubt about the performance. I'm not sure that I use well the connection.
Here my client script (jade template language):
!!! 5
html
head
title Foo
script(type='text/javascript', src='/javascript/socket.io.min.js')
script(type='text/javascript')
socket = new io.Socket('localhost', 3000);
socket.connect();
socket.on('message', function(data) {
});
body
This script is loaded on each page (because it's my layout page). So on each page, the socket connects to the server socket. That's my problem, I don't like this idea.
Is it possible to connect once the client socket to the server socket for every client's pages ?
In addition, is it possible to load once (per client) the /javascript/socket.io.min.js
library ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看pjax,希望对您有所帮助。
Check pjax, I hope it will help you.
为什么不让服务器将页面数据流式传输到客户端(通过 AJAX 调用或使用套接字),并在用户单击链接时将内容
div
替换为页面数据?不要使用
a href="my_page"
,而是使用a href="#my-page"
,并在所有a
上添加点击事件侦听器查看document.location.hash
来确定内容的元素用户尝试访问的“页面”。您还需要查看document.location.hash
当您首次加载页面时,以防用户直接访问末尾带有#my_page
的 URL。如果您希望“自然”网址按预期运行(例如
GET /my_page
),您可以让服务器在处理POST
请求时以 AJAX 调用方式进行响应,但每当使用GET
时,都会返回完整页面,其中预填充了主要div
内容。Why not have the server stream the page data to the client (either with AJAX calls or using your socket) and replace a content
div
with the page data whenever the user clicks a link?Instead of using
a href="my_page"
, usea href="#my-page"
, and add click event listeners on alla
elements that look atdocument.location.hash
to determine what "page" the user is trying to visit. You will also need to look atdocument.location.hash
when you first load the page in case the user is directly visiting a URL with#my_page
at the end.If you want "natural" urls to behave as expected (eg.
GET /my_page
), you can have the server respond as an AJAX call when it handles aPOST
request, but returns the full page with the maindiv
contents pre-populated wheneverGET
is used.