DEV Community

Cover image for Super small socket.io
Daniel Lukonis
Daniel Lukonis

Posted on

2

Super small socket.io

Hey friends!

I looked far and wide on the web to find a very minimal socket.io implementation. No express, no node http module, just socket.io. I couldn't find a suitable example so I wrote one. I plan on using a version of this on my upcoming MMORPG 2D space sim. Link to the repo here: minsocketio


Clone the repo:

git clone git@github.com:daniellukonis/minsocketio.git
Enter fullscreen mode Exit fullscreen mode

Install the dependencies with:

npm i
Enter fullscreen mode Exit fullscreen mode

then start both the server and client with:

npm start
Enter fullscreen mode Exit fullscreen mode

io.server.js

const io = require("socket.io")(13555)
  .on("connection", (socket) => {
    socket.on("data", data => io.emit("newData", data))
  })
Enter fullscreen mode Exit fullscreen mode

This creates the socket.io server and listens on port 13555. All it does right now is listens for connected clients to send a message labeled data, and rebroadcasts it to all connected clients.


io.client.mjs

import { io } from "socket.io-client"
const socket = io("ws://localhost:13555")
socket.on("newData", newData => console.log(newData))

setInterval(data, 1000)
function data() {
  const d = Math.random()
  socket.emit("data", d)
}
Enter fullscreen mode Exit fullscreen mode

This client simply connected to the socket.io server and sends a random number. It listens for the server to broadcast a message labeled newData, then logs it to the console.


Thanks for reading! Keep your ears open for progress on my game. I expect to stream some updates soon!

Thanks,
Daniel

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay