简体   繁体   English

如何使我的服务器可供所有人使用?

[英]How can I make my server accessible for everyone?

I created (I copied) a chat server using Node.JS and the server is on my LocalHost: 127.0.0.1 , only I can use the chat, but I want that anyone can use the server too, so I want to know how to put this Chat server in my real server: http://sistema.agrosys.com.br/sistema/padrao/HTML5/WebSocket/ 我使用Node.JS创建(复制)了一个聊天服务器,并且该服务器位于我的LocalHost上: 127.0.0.1 ,只有我可以使用该聊天,但是我希望任何人都可以使用该服务器,所以我想知道如何将此聊天服务器放在我的真实服务器中: http : //sistema.agrosys.com.br/sistema/padrao/HTML5/WebSocket/
And : http://calnetaskmanager.herokuapp.com/ 和: http : //calnetaskmanager.herokuapp.com/


But I don't now how to put my chat-server.js into my Heroku Server. 但是我现在不知道如何将chat-server.js放入Heroku Server中。

What should I do to make it possible. 我应该怎么做才能使其成为可能。

Thanks in advance 提前致谢

在此输入图像描述

If you want to see what happens: client side on my server 如果您想了解发生了什么: 我服务器上的客户端


Client Side: 客户端:

 $(function() { "use strict"; // for better performance - to avoid searching in DOM var content = $('#content'); var input = $('#input'); var status = $('#status'); // my color assigned by the server var myColor = false; // my name sent to the server var myName = false; // if user is running mozilla then use it's built-in WebSocket window.WebSocket = window.WebSocket || window.MozWebSocket; // if browser doesn't support WebSocket, just show some notification and exit if (!window.WebSocket) { content.html($('<p>', { text: 'Sorry, but your browser doesn\\'t ' + 'support WebSockets.' })); input.hide(); $('span').hide(); return; } // open connection var connection = new WebSocket('ws://127.0.0.1:1337'); connection.onopen = function() { // first we want users to enter their names input.removeAttr('disabled'); status.text('Choose name:'); }; connection.onerror = function(error) { // just in there were some problems with conenction... content.html($('<p>', { text: 'Sorry, but there\\'s some problem with your ' + 'connection or the server is down.' })); }; // most important part - incoming messages connection.onmessage = function(message) { // try to parse JSON message. Because we know that the server always returns // JSON this should work without any problem but we should make sure that // the massage is not chunked or otherwise damaged. try { var json = JSON.parse(message.data); } catch (e) { console.log('This doesn\\'t look like a valid JSON: ', message.data); return; } // NOTE: if you're not sure about the JSON structure // check the server source code above if (json.type === 'color') { // first response from the server with user's color myColor = json.data; status.text(myName + ': ').css('color', myColor); input.removeAttr('disabled').focus(); // from now user can start sending messages } else if (json.type === 'history') { // entire message history // insert every single message to the chat window for (var i = 0; i < json.data.length; i++) { addMessage(json.data[i].author, json.data[i].text, json.data[i].color, new Date(json.data[i].time)); } } else if (json.type === 'message') { // it's a single message input.removeAttr('disabled'); // let the user write another message addMessage(json.data.author, json.data.text, json.data.color, new Date(json.data.time)); } else { console.log('Hmm..., I\\'ve never seen JSON like this: ', json); } }; /** * Send mesage when user presses Enter key */ input.keydown(function(e) { if (e.keyCode === 13) { var msg = $(this).val(); if (!msg) { return; } // send the message as an ordinary text connection.send(msg); $(this).val(''); // disable the input field to make the user wait until server // sends back response input.attr('disabled', 'disabled'); // we know that the first message sent from a user their name if (myName === false) { myName = msg; } } }); /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { status.text('Error'); input.attr('disabled', 'disabled').val('Unable to comminucate ' + 'with the WebSocket server.'); } }, 3000); /** * Add message to the chat window */ function addMessage(author, message, color, dt) { content.prepend('<p><span style="color:' + color + '">' + author + '</span> @ ' + +(dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':' + (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) + ': ' + message + '</p>'); } }); 
 * { font-family: tahoma; font-size: 12px; padding: 0px; margin: 0px; } p { line-height: 18px; } div { width: 500px; margin-left: auto; margin-right: auto; } #content { padding: 5px; background: #ddd; border-radius: 5px; overflow-y: scroll; border: 1px solid #CCC; margin-top: 10px; height: 160px; } #input { border-radius: 2px; border: 1px solid #ccc; margin-top: 10px; padding: 5px; width: 400px; } #status { width: 88px; display: block; float: left; margin-top: 15px; } 
 <!DOCTYPE html> <html> <head> <style type="text/css"></style> <meta charset="utf-8"> <title>WebSockets - Simple chat</title> </head> <body> <div id="content"></div> <div> <span id="status">Choose name:</span> <input type="text" id="input"> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="./frontend.js"></script> </body> 

Server Side 服务器端

// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
"use strict";

// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'node-chat';

// Port where we'll run the websocket server
var webSocketsServerPort = 1337;

// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');

/**
 * Global variables
 */
// latest 100 messages
var history = [];
// list of currently connected clients (users)
var clients = [];

/**
 * Helper function for escaping input strings
 */
function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')
        .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

// Array with some colors
var colors = ['red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange'];
// ... in random order
colors.sort(function(a, b) {
    return Math.random() > 0.5;
});

/**
 * HTTP server
 */
var server = http.createServer(function(request, response) {
    // Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
    console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});

/**
 * WebSocket server
 */
var wsServer = new webSocketServer({
    // WebSocket server is tied to a HTTP server. WebSocket request is just
    // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
    httpServer: server
});

// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
    console.log((new Date()) + ' Connection from origin ' + request.origin + '.');

    // accept connection - you should check 'request.origin' to make sure that
    // client is connecting from your website
    // (http://en.wikipedia.org/wiki/Same_origin_policy)
    var connection = request.accept(null, request.origin);
    // we need to know client index to remove them on 'close' event
    var index = clients.push(connection) - 1;
    var userName = false;
    var userColor = false;

    console.log((new Date()) + ' Connection accepted.');

    // send back chat history
    if (history.length > 0) {
        connection.sendUTF(JSON.stringify({
            type: 'history',
            data: history
        }));
    }

    // user sent some message
    connection.on('message', function(message) {
        if (message.type === 'utf8') { // accept only text
            if (userName === false) { // first message sent by user is their name
                // remember user name
                userName = htmlEntities(message.utf8Data);
                // get random color and send it back to the user
                userColor = colors.shift();
                connection.sendUTF(JSON.stringify({
                    type: 'color',
                    data: userColor
                }));
                console.log((new Date()) + ' User is known as: ' + userName + ' with ' + userColor + ' color.');

            } else { // log and broadcast the message
                console.log((new Date()) + ' Received Message from ' + userName + ': ' + message.utf8Data);

                // we want to keep history of all sent messages
                var obj = {
                    time: (new Date()).getTime(),
                    text: htmlEntities(message.utf8Data),
                    author: userName,
                    color: userColor
                };
                history.push(obj);
                history = history.slice(-100);

                // broadcast message to all connected clients
                var json = JSON.stringify({
                    type: 'message',
                    data: obj
                });
                for (var i = 0; i < clients.length; i++) {
                    clients[i].sendUTF(json);
                }
            }
        }
    });

    // user disconnected
    connection.on('close', function(connection) {
        if (userName !== false && userColor !== false) {
            console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
            // remove user from the list of connected clients
            clients.splice(index, 1);
            // push back user's color to be reused by another user
            colors.push(userColor);
        }
    });

});

您需要将Node.js代码托管在某个地方,例如在Heroku上 ,他们有免费的Node.js计划,然后将为您提供一个公共URL,您可以将该URL分发给其他人

Make it available to everyone... This is easy. 将其提供给所有人...这很容易。

  1. Deploy your code to a publicly available host -- say Heroku as mentioned by @dark_ruby in his answer. 将您的代码部署到可公开使用的主机上-说出@dark_ruby在回答中提到的Heroku。

  2. Provide a computing device with a browser (a nexus 7 will do) to every person in the entire world 为全世界的每个人提供一个带有浏览器的计算设备(将使用nexus 7)

  3. Configure it to have your service as the default home page 配置它以将您的服务作为默认主页

Done. 完成。

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

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