简体   繁体   English

我可以将基于node.js / express的聊天集成到基于PHP / jquery的网站中吗?

[英]Can I integrate a node.js/express based chat into my PHP/jquery based site?

I have an established site that I want to make chat client for. 我有一个我想为其建立聊天客户端的站点。 I want to write it all myself for fun and to learn a little about node.js and express. 我想自己编写所有内容,以娱乐并了解有关node.js和表达的知识。 Right now I have a chat system based on jQuery/PHP/MySQL and polling with ajax. 现在,我有一个基于jQuery / PHP / MySQL的聊天系统,并使用ajax进行轮询。 It is slow and I only poll every 5 seconds so it looks slow too. 它很慢,我每5秒才轮询一次,所以它看起来也很慢。

I can write the chat in node.js, but my question is: How can I include my chat in the my oldschool pages. 我可以在node.js中编写聊天记录,但是我的问题是:如何在我以前的学校页面中包含聊天记录。 I want it to be a box that is at the bottom corner of all my pages. 我希望它是我所有页面底角的一个框。 I am not concerned with the css, only how to integrate it. 我不关心css,只关心如何集成它。 Should the chat live at it's own domain (chat.example.com) and just allow cross site access? 聊天应该在其自己的域(chat.example.com)中进行,只允许跨站点访问吗?

Here is a reference to the Access Control Headers. 这是对访问控制标头的引用。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

If your PHP app is running say behind nginx. 如果您的PHP应用程序正在运行,请在nginx之后说。 You could set up a route in nginx that forwards those requests to the chat server. 您可以在nginx中设置一条路由,将那些请求转发到聊天服务器。

Here is an example: 这是一个例子:

upstream app_chat {
    server 127.0.0.1:8080;
}

server {
    listen 0.0.0.0:80;
    server_name www.mydomain.com mydomain;

    location /chat {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://app_chat/;
        proxy_redirect off;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

So from your client js 所以从您的客户端js

var sock = io.connect('ws://mydomain/chat');
sock.on('chat', function (msg) {
  console.log('msg', msg);
});

Yes, you can. 是的你可以。 I don't know how complex your app is. 我不知道您的应用程序有多复杂。 But, running a node server on a different port will do. 但是,可以在其他端口上运行节点服务器。

Lets say your PHP app runs on port 80. Now, run your node.js server which handles the chat system on 8080. Then in your PHP page, include a JS file(chat.js). 假设您的PHP应用程序在端口80上运行。现在,运行在8080上处理聊天系统的node.js服务器。然后在您的PHP页面中,包含一个JS文件(chat.js)。

chat.js chat.js

var connection = io.connect('YOUR_NODE_SERVER_URL'); //like http://localhost:8080

/*
your code
*/

That's it. 而已。

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

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