第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
如有任何疑问,请在下面发表评论。 。
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.
thanks
You don't need to generate socket.id, socket.io already does that for you
Awesome!
просто заебись! =) thanks for lessons!
I found an issue with the disconnect code. If you spam reload on one of the clients, their player instances won't delete… any ideas on fixing that?
The examples are easy to understand on quite a difficult topic. Love it.
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! )
My letter stops moving in the current tab after loading the page in another tab… does anyone know why?
my terminal won't execute because of the line y:socket.y. any idea why?
great tutorial, thanks
This is a great tutorial. But rather than sending me to the next video youtube sends me to another channel. So scummy.
Hey there, you can use socket.id to grab the package generated id for the socket, instead of doing Math.random().
Amazing tutorial, straight to the point and very well demonstrated. Thank you !
That da mned "P" don't want to walk -,- …
speed to 0.25, skip to 6:28 and watch closely
how do you update the server? i always have to close cmd then open it again.
Thank you so much for the tutorial RC! Working on an IO game, and this is helping out a lot with getting started.
Code not working and your explanations make it difficult to trouble shoot where the error is.
I love this tutorial but have an issue, the socket connection message no longer shows after adding the code from Ep. 2
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?
I am loving this tutorial, I have been looking for something like this for a while, thanks for the great explanations! 🙂
the link to the previous video is wrong, it sending you to the singleplayer serie, not the multiplayer one
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!
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.
For those who want their games to handle as many players as possible (code performance), it's worth to mention to use arrays instead of objects for commonly used loops (in this example, I would make SOCKET_LIST to be an array [], not an object {}). Performance comparison: https://jsperf.com/performance-of-array-vs-object/17
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 :/
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?
Another problem: the numbers are not displayed, there is not one error in the console
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);
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>'😉
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
Suck its lol
It's a best tutorial. Laconically, "without water"
AMAZINGG
is this code available somewhere? i cannot locate the missing comma.
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!
how do i update the server? i always quit out of cmd and then do cd C:UsersMalteBrowser_Gamesproject then node app.js
This is so cool
I cant run the two side by side. As soon as I open a second connection the first one stops. Only one seems to run at a time.
OMG. amazing!!
Hey RC, I am hoping you are able to help me with an error I am receiving after typing the code between 7:13 – 8: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
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)
continue make good videos
thanks!
Yo thanks dude! Helped a lot on the understanding of socket.io and node.js. Only thing that bothers me is the way you say "Happy".
Great tutorials, thanks!
Thanks for these great tutorials.