在 nodejs socket.io 中显示连续连接消息 [英] Show continuous connection message in nodejs socket.io

查看:27
本文介绍了在 nodejs socket.io 中显示连续连接消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Laravel 开发实时聊天应用程序.我面临一个问题.当我运行 "node index.js" 时,'A connection has made' 消息在命令提示符中持续显示.

我的 index.js 文件是:

var app = require('express')();var server = require('http').Server(app);var io = require('socket.io')(server);服务器.听(3000);app.get('/', function(request, response){response.sendFile(__dirname+ '/index.html');});io.on('连接', 函数(socket){console.log('一个连接已经建立');//socket.on('chat.message', function(message){//io.emit('chat.message', message);//});});

我的 index.html 页面是:

<头><title>在线聊天</title><身体><div class="container" id="chat"><h1>聊天系统</h1>

<script type="text/javascript">var socket = io();

我该如何解决?

解决方案

您的客户端不断地反复尝试连接的通常原因是因为您的 socket.io 客户端和服务器版本不匹配,使它们不兼容.您没有展示如何在网页中加载 socket.io Javascript,但如果您这样做:

然后,您将始终自动从您的服务器获取与您的服务器完全匹配的版本(这是 socket.io 服务器自动添加到您的 Express 服务器的路由).

如果您是从 CDN 加载 socket.io,那么您必须切换到上述内容从您自己的服务器加载它,或者从 CDN 手动指定与您在服务器上运行时完全相同的版本.

>

I am trying to develop a live chat application using laravel. I face a problem. When I run "node index.js" , 'A connection has made' message has shown continuously in command prompt.

my index.js file is:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);
app.get('/', function(request, response){
    response.sendFile(__dirname+ '/index.html');        
});

io.on('connection', function(socket){
    console.log('A connection has made');
    // socket.on('chat.message', function(message){
    //  io.emit('chat.message', message);
    // });
});

My index.html page is:

<!DOCTYPE html>
<html>
    <head>
        <title>Live Chat</title>
    </head>
    <body>
        <div class="container" id="chat">
            <h1> Chat System </h1>
        </div>
    <script type="text/javascript">
    var socket = io();
    </script>
    </body>
</html>

How can I solve it?

解决方案

The usual reason that your client is continually trying to connect over and over again is because you have a mismatched client and server version of socket.io making them incompatible. You don't show how you load the socket.io Javascript in your web page, but if you do it like this:

<script src="/socket.io/socket.io.js"></script>

Then, you will always get the version that exactly matches your server from your server automatically (this is a route that the socket.io server automatically adds to your Express server).

If you are loading socket.io from a CDN, then you have to either switch to the above to load it from your own server or manually specify the exact same version from the CDN as you are running on the server.

这篇关于在 nodejs socket.io 中显示连续连接消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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