简体   繁体   中英

How can I connect to an established server (NOT localhost) with node.js & socket.io?

I am very new to web servers / node.js / socket.io and I'm trying to make a very simple website just to learn how to connect 2 people. All of the tutorials I've found teach you how to run your app on localhost, but I want to run it on a server so everyone can access it.

I found this hosting website - Zeit-Now - and managed to put my website online. My website works just fine on localhost, but I can't get it to work when i put it online. I think the problem is in these 2 lines in my code, where the '???' are.

index.html:

<!DOCTYPE html>

<html>

<head>
    <title>A2</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
</head>

<body>
    <input id="sendMsg" type="text" placeholder="TYPE TO SEND">
    <input id="receiveMsg" type="text" placeholder="RECEIVE HERE">
    <button id="sendBtn">Send</button>

    <script>

var socket = io.connect('https://web-socket-2.quaei.now.sh/');

var sendMsg = document.getElementById('sendMsg');
var receiveMsg = document.getElementById('receiveMsg');
var sendBtn = document.getElementById('sendBtn');

// Emit events
sendBtn.addEventListener('click', () => {
    socket.emit('chat', {
        message: sendMsg.value
    });
});

// Listen for events
socket.on('chat', data => {
    receiveMsg.value = data.message;
});

    </script>
</body>

</html>

index.js:

const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);

app.use(express.static('public'));

io.on('connection', socket => {
    console.log('Connection! ->', socket.id);

    socket.on('chat', data => {
        io.sockets.emit('chat', data);
    });
});

I've also tried:

var socket = io.connect(https://web-socket-2.quaei.now.sh/);

and

var server = app.listen(80, https://web-socket-2.quaei.now.sh/);

I expect my website to read what is written in the first input field and output it in the second one when clicked send (which works fine on localhost), but it doesn't work when I put it online with Zeit-Now.

Edit:

now.json:

{
    "version": 2,
    "name": "web-socket-2",
    "builds": [{
            "src": "public/**/*",
            "use": "@now/static"
        },
        {
            "src": "*.js",
            "use": "@now/node"
        }
    ],
    "routes": [{
        "src": "/",
        "dest": "public/index.html"
    }]
}

I have a #websocket-2 folder with now.json , index.js and public folder. In public folder I have index.html .

How can I make it work on this website: https://web-socket-2.quaei.now.sh/ ?

I guess the problem you face at the moment is that you want to run the server directly on the website. But it's need to be run by node like this: node index.js .
Therefore you need access to the server like some ssh access and then start it there with the command named above. Based on the logs, I can say that the client can't find the server.
You also need to make sure that it resolves to the right path.
Start it with app.listen(80) and then try to connect to https://web-socket-2.quaei.now.sh:80

try this

const app = express();

const server = http.createServer(app);

const io = socketio(server);

server.listen(80, '0.0.0.0');

Make sure your server has websockets enabled. (It does not actually need websockets, but it will use it if possible for better transport)

Reading about zeit.co I can see they dont support websockets, not sure if they support sucket either. I would recommend you hitting them up with email to confirm this if code below does not help you.

To run connection on client side, after you have installed socket.io-client or after you have included script in header, which you have.

You simply connect using io.connect('SERVER URL') which will return your socket connection instance. (no need to pass server if running on same server)

const socket = io.connect('http://youserver.com'); 
// You can listen to conenct and disconnect to track your connection
socket.on('connect', socket => {
    console.log('Connected', socket.id); 
});

Thats it on client side.

On server side, you need to pass server to your socket.io module

const io = require('socket.io')(server);
// You can listen to your socket connecting through connect and disconnect
io.on('connect', (socket) => {
  console.log('socket connected', socket);
});

You can track your errors on client side using 'error' event, and make sure to check your console to see the logs about the connection.

In case you are using express server, and socket is raising 404 errors in console, make sure you initiate server using http instead of express.

const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server); 

// your socket and routes

server.listen(process.env.PORT || 3500, () => {
   console.log(`Localhost working on ${process.env.PORT || 3500}`);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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