How do I deploy socket.io to Google App Engine?

前端 未结 4 1500
庸人自扰
庸人自扰 2020-12-23 22:30

I created my first node.js app using socket.io. Specifically I implemented the chat example published by socket.io. It works perfectly, locally. And then I tried deploying i

4条回答
  •  旧巷少年郎
    2020-12-23 22:51

    Google has an example app using WebSockets here, you need to do the following to get it working correctly:

    • Open up a firewall port for the server so clients can reach your server
    • Fetch your internal IP in Google App Engine, so clients know what IP to connect to
    • Echo out your IP from your server via something like a rest API or a HTML page

    That should be it (don't take my word for it though, this is what I've been able to find out after doing some research on the docs), hope it helps!

    Fetching your external IP from within Google App Engine

    var METADATA_NETWORK_INTERFACE_URL = 'http://metadata/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip';
    
    function getExternalIp (cb) {
        var options = {
            url: METADATA_NETWORK_INTERFACE_URL,
            headers: {
                'Metadata-Flavor': 'Google'
            }
        };
    
        request(options, function (err, resp, body) {
            if (err || resp.statusCode !== 200) {
                console.log('Error while talking to metadata server, assuming localhost');
                return cb('localhost');
            }
    
            return cb(body);
        });
    }
    

    Opening the firewall port

    gcloud compute firewall-rules create default-allow-websockets \
        --allow tcp:65080 \
        --target-tags websocket \
        --description "Allow websocket traffic on port 65080"
    

提交回复
热议问题