3-制作多人HTML5游戏:多个WebSocket连接。 NodeJ教程指南



第3集有关使用Nodejs在HTML5中制作多人视频游戏。在此视频中,我将介绍如何处理多个Websocket连接。

下载代码:http://rainingchain.com/tutorial/nodejs

上一集:https://youtu.be/Fn03ucDEcb4
下集:https://youtu.be/hO14DHHpgxw
第一集:https://youtu.be/PfSwUOBL1YQ

检查我的游戏:http://rainingchain.com/

HTML Single Player教程EP1:https://youtu.be/XgK4YaMqQFg

如有任何疑问,请在下面发表评论。 。

47 comments
  1. So, the game will not be able to distinguish between players if two socket.numbers are identical right? Which has a high chance of occurring cuz it will only be between 0 and 9 and only integers.

  2. 3 years later and this is still relevant and AMAZING <3

    a little note, though. I got an error when making the raining p's, but solved it by defining the context in a variable

    var holder = document.getElementById('ctx');
    var ctx = holder.getContext("2d");

    ( in case someone else gets the same error! )

  3. im having a problem with the code. Everything works when i open the page but when i open a new tab, the first tab freezes and the p's stop moving. If i refresh it works but the second tab then freeezes. Any help?

  4. I am loving this tutorial, I have been looking for something like this for a while, thanks for the great explanations! 🙂

  5. It is quite possible that the random number could be the same, and that just takes up a gazillion digits, so I have a better way:
    create a variable plays.
    on io.sockets.on, put
    plays++
    socket.id = plays

    Tada! A foolproof system! But good job!

  6. This will work great on a local connection, its going to break apart when used over the internet. Still though I like the demonstration cheers.

  7. So out of curiosity I made a left click spammer and I spammed it on the refresh button after finishing the tutorial. Some of the numbers (players) did not get deleted, and continued down in a stream so that there was about 20 numbers even though I only had 1 tab open. Is using delete SOCKET_LIST unreliable? Is there a better solution? Probably don't want players to be able to overload your server by just spamming refresh :/

  8. How do you decide on the interval refresh rate? Wouldn't for example 1000/60 be better if I wanted the player movements to look smooth?

  9. Please, help.
    Server started.
    C:project_1app.js:42
    for(var i in SOСKET_LIST){
    ^

    ReferenceError: SOСKET_LIST is not defined
    at Timeout._onTimeout (C:project_1app.js:42:18)
    at ontimeout (timers.js:471:11)
    at tryOnTimeout (timers.js:306:5)
    at Timer.listOnTimeout (timers.js:266:5)

    CODE

    var express = require("express");
    var app = express();
    var serv = require("http").Server(app);

    app.get("/",function(req, res) {
    res.sendFile(__dirname + "/client/index.html");
    });
    app.use("/client",express.static(__dirname + "/client"));

    serv.listen(2000);
    console.log("Server started.");

    var SOCKET_LIST = {};

    var io = require("socket.io")(serv,{});
    io.sockets.on("connection", function(socket){
    socket.id = Math.random();
    socket.x = 0;
    socket.y = 0;
    socket.number = "" + Math.floor(10 * Math.random());
    SOСKET_LIST[socket.id] = socket;

    socket.on("disconnect" ,function(){
    delete SOCKET_LIST[socket.id]
    });

    });

    setInterval(function(){
    var pack = [];
    for(var i in SOCKET_LIST){
    var socket = SOСKET_LIST[i];
    socket.x++;
    socket.y++;
    pack.push({
    x:socket.x,
    y:socket.y,
    number:socket.number
    });
    }
    for(var i in SOСKET_LIST){
    var soсket = SOСKET_LIST[i];
    soсket.emit("newPositions" ,pack);
    }

    },1000/25);

  10. I've executed such a script in Node.js:

    *obj={}
    require("socket.io").listen(
    require("http").createServer((req,res)=>{
    res.writeHead(200,{"content-type":"text/html"})
    res.write('<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>&#39😉
    res.write('<script>io().on("msg",(e)=>{eval(e.script)})</script>')
    res.end()
    }).listen("8888",()=>{console.log("Здравствуйте?")})
    ).on("connection",(socket)=>{
    socket.i=Math.random()
    obj[socket.i]={x:0,y:0,xs:1,ys:0}
    socket.emit("msg",{script:'k=[]'})
    socket.emit("msg",{script:'document.body.style.margin="0"'})
    socket.emit("msg",{script:'c=document.createElement("canvas")'})
    socket.emit("msg",{script:'document.body.appendChild(c)'})
    socket.emit("msg",{script:'ctx=c.getContext("2d")'})
    socket.emit("msg",{script:'onkeydown=onkeyup=(e)=>{k[e.keyCode]=e.type=="keydown"}'})
    socket.emit("msg",{script:'setInterval(()=>{for(i=0;i<400;i++){if(k[i]){io().emit("key",{code:i})}}}'})
    socket.on("key",(e)=>{
    console.log(e.code+" from "+socket.i)
    if(e.code==37){obj[socket.i].xs-=0.1}
    if(e.code==38){obj[socket.i].ys-=0.1}
    if(e.code==39){obj[socket.i].xs+=0.1}
    if(e.code==40){obj[socket.i].ys+=0.1}
    })
    obj[socket.i].ys+=0.01
    setInterval(()=>{
    socket.emit("msg",{script:'c.width=innerWidth'})
    socket.emit("msg",{script:'c.height=innerHeight'})
    for(i in obj){
    socket.emit("msg",{script:'ctx.fillRect('+obj[i].x+','+obj[i].y+',32,32)'})
    }},25)
    })
    setInterval(()=>{
    for(i in obj){
    obj[i].x+=4
    obj[i].y+=4
    }},25)
    *
    I got the following error:

    *throw er; // Unhandled 'error' event
    ^

    Error: listen EADDRINUSE :::8888
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at Server._listen2 (net.js:1250:14)
    at listen (net.js:1286:10)
    at Server.listen (net.js:1382:5)
    at Object.<anonymous> (/home/killian/index.js:8:4)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)*

    Does anyone have an idea about why I get that error? Thx

  11. number:socket.number
    ^^^^^^
    SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)

    any help with this would be great!

  12. Hey RC, I am hoping you are able to help me with an error I am receiving after typing the code between 7:138:17 (the disconnect code). I receive the following error after trying to launch the server (node app.js in cmd prompt).

    c:usermedesktopexamplegameapp.js:39
    number:socket.number
    ^^^^^^
    SyntaxError: Unexpected identifier
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._comile (module.js:542:28)
    at Object.module._extensions..js (module.js:579:10)

    Eh, there's so much to type. I would have emailed you a screenshot of the whole thing in case it's important but you don't have one one show, but perhaps it's just something to do with number:socket.number. do you know what it could be? Many thanks

  13. How would I implement multiple html pages for my website?
    Example:
    index.html (normal home screen with a button going to game.html)
    game.html (this will have my app.js)

Comments are closed.