Ping Pong game with php socket and html canvas
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

ping pong socket

Ping Pong game with php socket and html canvas



Persian document

You can read this document in persian with This Link


First , you should copy files in your localhost ( that can be create with Xampp ) .
Then just open server.php and index.php files to edit server and port address .
Run your server.php file in browser .
Then you can open index.php file and enjoy from game ( game starts after second user ) .

General structure

First , visitors connect to server with this code in index.php and server determine turn and side of user .

	var wsUri = "ws://"; 	
	websocket = new WebSocket(wsUri);
	websocket.onopen = function(ev) { 
        toastr["info"]("socket is ok !")

	websocket.onmessage = function(ev) {
		var msg = JSON.parse(; //PHP sends Json data
		var type = msg.type; 
		var umsg = msg.message; 
		var uname =;
		var go = msg.gameover;
		if(type == 'system')
                turn = uname;
                toastr["info"]("You are : "+turn+" side . Hope enjoy")
             if(go==1) gameover=0;
             else gameover=1;

		else {
			eval(uname+'_racket').y = umsg;

	websocket.onerror	= function(ev){toastr["error"](};
	websocket.onclose 	= function(ev){toastr["error"]('Close')};

Canvas components

All the elements in the game defined in this code .

function startGame() {
    right_racket = new component(65, 65, "images/right_racket.png", right_line-10, center_line,"image");
    left_racket = new component(65, 65, "images/left_racket.png",left_line-30, center_line,"image");
    ball = new component(25, 25, "images/ball.png", eval(side+'_line'), center_line+20 ,"image");
    right_score = new component("30px", "IranYekan", "red", 310, 140, "text");
    left_score = new component("30px", "IranYekan", "blue", 180, 140, "text");
    sound_strike 	= new sound("sounds/strike.mp3");
    sound_gameover   = new sound("sounds/gameover.mp3");
    sound_shoes1	= new sound("sounds/shoes2.mp3");
    sound_shoes2	= new sound("sounds/shoes1.mp3");

For a better understanding of html canvas games , please read this tutorial by w3schools

I just send the rackets position in socket . you can send ball and results too .

function send_packet(ja){
   	var msg = {
   	message: ja,
   	name: turn,

You can change game speed in this line :

this.interval = setInterval(updateGameArea, 10);

Thanks .

Code by : Farid Froozan ( as university project ( Computer Networks )