【问题标题】:Chat Server With NodeJS and Socket.io使用 NodeJS 和 Socket.io 的聊天服务器
【发布时间】:2014-06-20 02:38:53
【问题描述】:

我已经为服务器编写了这个脚本

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(3000);

app.get('/' , function(req,res){
    res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection' , function(socket){
    socket.on('send message' , function(data){
        io.sockets.emit('new message' , data);
    });
});

这是聊天页面

<html>
<head>
<title>Chat Program</title>
<style>
#chat{
height:400px;
}
</style>

    <script src="http://code.jquery.com/jquery-latest-min.js"></script>
    <script src="/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
    <script>
        jQuery(function($){
            var socket = io.connect();
            var $messageform = $('#send-message');
            var $messagebox = $('#message');
            var $chat = $('#chat');

            $messageform.submit(function(e){
                e.preventDefault();
                socket.emit('send message' , $messagebox.val());
                $messagebox.val("");
            });

            socket.on('new message' , function(data){
                $chat.append(data + "<br/>");
            });
        });
    </script>
</head>
<body>
    <div id="chat"></div>
    <form id="send-message">
        <input size="35" id="message"></input>
        <input type="submit"></input>
    </form>
</body>
</html>

当我从控制台运行脚本时,它运行良好,但是当我在聊天框中写东西时,什么也没有发生...我不知道为什么但我认为我从“npm install socket.io”下载的文件夹-client”有问题。

这条线 ==> &lt;script src="/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"&gt;&lt;/script&gt;我认为问题就在这里,因为整个代码是正确和正确的(我认为)

提示:我是 Node.js 初学者

【问题讨论】:

  • node_modules 在您的公共文件夹中吗?如果没有,您的网页将永远不会获得该文件。将其符号链接到您的公用文件夹中,您应该很好
  • 这里的脚本在同一个文件夹中 ==> i.imgur.com/Jgkxqj2.jpg

标签: node.js sockets


【解决方案1】:

您没有将 express 配置为提供文件。您有 2 个选项。你可以:

  1. 配置 express 以显式提供该文件

    将此添加到您的应用文件中:

    app.get('/socket.io.js' , function(req,res){
        res.sendfile(__dirname + '/node_modules/socket.io/node_modules/socket.io-client/socket.io.js');
    });
    

    并将您的 html 脚本切换为:

    <script src="/socket.io.js"></script>
    
  2. 配置 express 以服务器目录中的任何文件(请参阅this

【讨论】:

  • 是的,看起来应该这样做。你也需要改变你的 HTML
猜你喜欢
  • 1970-01-01
  • 2013-08-08
  • 2012-01-29
  • 2016-05-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
  • 2015-04-14
  • 2013-04-04
相关资源
最近更新 更多