简体   繁体   English

简单的node.js聊天服务器问题

[英]Simple node.js chat server issues

Im having issues with a node.js server and HTML client. 我在使用node.js服务器和HTML客户端时遇到问题。

The server code is: 服务器代码为:

var http = require('http');
    fs = require('fs');

var app = http.createServer(function(request, response) {
    fs.readFile("client.html", 'utf-8', function (error, data) {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    }); 
}).listen(1337);

var io = require('socket.io').listen(app);

io.sockets.on('connection', function(socket)    {
    socket.on('message_to_server', function(data)   {
        io.sockets.emit("message_to_client",{ message: data["message"]});
    });
});
console.log('Server running')

And client code is: 客户代码为:

<!DOCTYPE html>
<html>
<head>
    <title>Rumors and speculations</title>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
        var socketio = io.connect("localhost", {port: 1337});

        socketio.on("message_to_client", function (data) {
            document.getElementById("chatlog").innerHTML = ("<hr/>" +
            data['message'] + document.getElementById("chatlog").innerHTML);
        });
        function sendMessage() {
            var msg = document.getElementById("message_input").value;
            socketio.emit("message_to_server", { message: msg });
        }
    </script>
</head>
<body>
    <input type="text" id="message_input" />
    <button onclick="sendMessage()">send</button>
    <div id="chatlog"></div>
</body>
</html>

I don't know if it makes a difference or not, but i am running my HTML from Visual Studio (building an ASP.NET MVC app). 我不知道它是否有所作为,但是我正在从Visual Studio运行HTML(构建ASP.NET MVC应用程序)。

I get the chat button and windows for typing on the screen, but when i add some text and click 'send' nothing happens, and nothing is displayed. 我在屏幕上看到聊天按钮和用于键入的窗口,但是当我添加一些文本并单击“发送”时,什么也没有发生,并且什么也没有显示。 Am I missing something? 我想念什么吗? I would almost bet that I am missing something in regards to the server adress, but I have stared myself blind to be able to find it. 我几乎敢打赌,我在服务器地址方面缺少一些东西,但是我一直盯着自己看不见,无法找到它。

In your client code: data['message'] + document.getElementById("chatlog"). 在您的客户端代码中:data ['message'] + document.getElementById(“ chatlog”)。 innterHTML is spelled incorrectly. innterHTML的拼写错误。 It should say .innerHTML 应该说.innerHTML

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

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