试图获得一个示例Node.js应用程序工作

Trying to get a sample Node.js application working

本文关键字:Node js 工作 应用程序 一个      更新时间:2023-09-26

我正在尝试使用node.js, express和socket.io运行一个基本的聊天应用程序。我已经成功地让一切运行到我没有得到任何错误在服务器端或客户端。但是,应用程序不能工作。
我应该能够打开两个浏览器窗口和自己聊天。我在文本框中输入要发送聊天消息给自己,但没有收到任何消息。我很确定也没有发送任何东西。使用FireBug时,我没有看到任何新的请求通过网络发送。但是,通过使用Firebug,我还看到所有请求的include文件都被正确地提供给了浏览器。只有三个:index.html、socket.io.js和jquery.min.js。

这是我正在使用的教程的链接:http://philmunt.com/post/15643013618/node-js-socket-io-chat-application-tutorial

对于server.js文件,我稍微修改了一下以使其工作。主要的问题是,我的浏览器没有接收socket.io.js,所以我添加了一个路径,让server.js知道它在哪里。是这样的:app.get (sio/socket.io.js,函数(点播,res ) {........这是我的问题吗?

服务器代码- server.js:

var express = require('express'), app = express(), http = require('http'), server = http.createServer(app), io = require('socket.io').listen(server);
// listen for new web clients:
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});         
app.get('/sio/socket.io.js', function (req, res) {
res.sendfile('/root/nodejs/node-v0.10.0/node_modules/socket.io/lib/socket.io.js');
});     
io.sockets.on('connection', function (socket) { socket.on('sendMessage', function (data) { socket.broadcast.emit('message', data); socket.emit('message', { text: '<strong>'+data.text+'</strong>' });   
 });   
 });

这是index.html文件:

<html> 
  <body>
    <script src="/sio/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        var socket = io.connect('http://localhost');
        socket.on('message', function (data) {
          $('#chat').append(data.text + '<br />');
        });
        $('#send').click(function () {
          socket.emit('sendMessage', { text: $('#text').val() });
          $('text').val('');
        });
      });
    </script>
    <div id="chat" style="width: 500px; height: 300px; border: 1px solid black">
    </div>    
    <input type="text" name="text" id="text">
    <input type="button" name="send" id="send" value="send">
  </body>
</html> 

删除app.get(socketstuff)部分,你不需要它,因为js文件已经为你提供了

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

并将套接字变量更改为:

var socket = io.connect();