DEV Community

Cover image for Fun with Sockets!
Dr Abstract
Dr Abstract

Posted on

Fun with Sockets!

Sockets are used in mulituser apps like chats, shared spaces, avatar based games, etc. They are the height of Interactive Media and tricky to code as you have to code for the current user and the other users in the same code.

Alt Text

Traditionally socket work is done on the server which means working with sockets can be daunting for front-end coders. We have made it easy with ZIM by abstracting common code to ZIM Socket Server running on Node and SocketIO. And then providing ZIM Socket on the front end. Get the code and see examples at

A. Before starting we need to import CreateJS and ZIM and then SocketIO and ZIM socket.js. We also include a zimserver_urls.js just in case the Socket server ever changes - so add this in the head of an HTML page:

<script src=""></script>
<script src=""></script>

<script src=""></script>
<script src=""></script>
<script src=""></script>
Enter fullscreen mode Exit fullscreen mode

B. Here is the ZIM Template to add underneath:

var scaling = "fit"; 
var width = 1024;
var height = 768;
var color = darker;
var outerColor = dark;
var frame = new Frame(scaling, width, height, color, outerColor);
frame.on("ready", function() {
    zog("ready from ZIM Frame");

    var stage = frame.stage;
    var stageW = frame.width;
    var stageH = frame.height;

    // put your code here:

}); // end of ready
<!-- canvas with id="myCanvas" is made by zim Frame -->
Enter fullscreen mode Exit fullscreen mode

C. And here is what that ZIM Socket code looks like for a shared ball! Add this under the "put your code here" then open up a couple browser windows and you can drag the ball in one and see it change in the other - or put it on a server and get a friend from across the world try it!

    // get the app name here:
    var appName = "balls";
    var socket = new zim.Socket(zimSocketURL, appName); 
    socket.on("ready", data=>{        
        zogg("socket connected");        
        const ball = new Circle(100, red)
            .loc(data.ball||{x:stageW/2, y:stageH/2})
        ball.on("pressmove", ()=>{
            socket.setProperty("ball", {x:ball.x, y:ball.y});
        socket.on("data", data=>{
Enter fullscreen mode Exit fullscreen mode

We have made lots of exciting things with ZIM Socket. See the examples at:

and here is a CodePen to try:

If you have not checked out the Canvas recently - you simply must! Here is the ZIM Dev Site and some In-depth Guides by Dr Abstract including Your Guide to Coding Creativity on the Canvas.

Discussion (0)