Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

javascript - How to use socket.io to communicate with another server when the actual page is being served by a localhost server?

I'm serving my page through localhost (XAMPP, Apache), and on my friend's physical server I run a node.js server that is used for communication with the page (a game).

This is the node.js server code:

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

io.sockets.on('connection', function (socket)
{
    socket.on("start", function (data)
    {
        console.log(data);
    });
});

It runs without any errors, but I don't know how to include the socket.io code into my webpage! How do I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Include a script tag in your page:

<script src="http://[YOUR IP]:1235/socket.io/socket.io.js">

And it will be served by your node.js server.

Apart from that, you can just follow the examples on socket.io, e.g.:

var socket = io.connect("http://[YOUR IP]:1235");

socket.emit("start", "LET'S GO!");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...