<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://classes.engineering.wustl.edu/cse330/index.php?action=history&amp;feed=atom&amp;title=Module5-SocketIO-Test</id>
	<title>Module5-SocketIO-Test - Revision history</title>
	<link rel="self" type="application/atom+xml" href="http://classes.engineering.wustl.edu/cse330/index.php?action=history&amp;feed=atom&amp;title=Module5-SocketIO-Test"/>
	<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module5-SocketIO-Test&amp;action=history"/>
	<updated>2026-11-15T19:30:26Z</updated>
	<subtitle>Revision history for this page on the wiki</subtitle>
	<generator>MediaWiki 1.34.4</generator>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse330/index.php?title=Module5-SocketIO-Test&amp;diff=3435&amp;oldid=prev</id>
		<title>Todd: Created page with &quot;AJAX is useful when one-way communication is satisfactory for your web application. However, what happens when you need two-way communication, like a chat client, collaborativ...&quot;</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse330/index.php?title=Module5-SocketIO-Test&amp;diff=3435&amp;oldid=prev"/>
		<updated>2026-02-24T14:34:55Z</updated>

		<summary type="html">&lt;p&gt;Created page with &amp;quot;AJAX is useful when one-way communication is satisfactory for your web application. However, what happens when you need two-way communication, like a chat client, collaborativ...&amp;quot;&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;AJAX is useful when one-way communication is satisfactory for your web application. However, what happens when you need two-way communication, like a chat client, collaborative whiteboard, live dashboard, or multiplayer game? AJAX isn't the tool for the job. This is where '''Socket.IO''' comes in.&lt;br /&gt;
&lt;br /&gt;
Socket.IO is a library that enables low-latency, bidirectional, event-based communication between the server and the client. One key advantage is that the server can send messages to the client without the client having to ask first (as is the case with traditional AJAX polling). As you learn Socket.IO, the Node.js idea of ''non-blocking I/O'' will become your best friend! :contentReference[oaicite:0]{index=0}&lt;br /&gt;
&lt;br /&gt;
== Installing Socket.IO ==&lt;br /&gt;
&lt;br /&gt;
Before you install Socket.IO, you need to install [[Node.JS]] (which includes npm). We strongly recommend using the current '''Node LTS'''.&lt;br /&gt;
&lt;br /&gt;
Socket.IO is installed per-project (locally). This means you should '''cd''' to the project folder where your server code will live, then run:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ npm init -y&lt;br /&gt;
$ npm install socket.io&lt;br /&gt;
&amp;lt;/source&amp;gt; :contentReference[oaicite:1]{index=1}&lt;br /&gt;
&lt;br /&gt;
'''Note on &amp;quot;global&amp;quot; installs:''' If you pass ''-g'' to ''npm install'', the package is installed globally. For course projects, avoid global installs unless you are very confident you understand why you need them. Local installs make your project portable and reproducible.&lt;br /&gt;
&lt;br /&gt;
== A note about modern Node (ES Modules) ==&lt;br /&gt;
&lt;br /&gt;
Modern Node.js uses '''ES Modules''' (import/export) instead of the older require() syntax.&lt;br /&gt;
&lt;br /&gt;
To enable ES Modules, add this line to your package.json:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;json&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;type&amp;quot;: &amp;quot;module&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you do not want to use ES Modules, you can still use CommonJS (require), but all examples below use modern ESM syntax.&lt;br /&gt;
&lt;br /&gt;
== Messaging ==&lt;br /&gt;
&lt;br /&gt;
Socket.IO works by having clients and servers send '''named events''' to each other.&lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
// Computer A:&lt;br /&gt;
socket.emit(&amp;quot;info&amp;quot;, {&lt;br /&gt;
  hello: &amp;quot;world&amp;quot;&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
// Computer B:&lt;br /&gt;
socket.on(&amp;quot;info&amp;quot;, (data) =&amp;gt; {&lt;br /&gt;
  console.log(data.hello);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Computer A could be ''either the client or the server'', and Computer B would be the other. When '''socket.emit(name, data)''' is called on either end, any listeners registered with '''socket.on(name, ...)''' on the other end will run and receive the data.&lt;br /&gt;
&lt;br /&gt;
This event-based model is inspired by Node's EventEmitter style: emit events on one side, listen on the other. :contentReference[oaicite:2]{index=2}&lt;br /&gt;
&lt;br /&gt;
== A First Socket.IO Application: Chat Server and Client ==&lt;br /&gt;
&lt;br /&gt;
Building a chat client is surprisingly simple using Socket.IO and Node.js, and it gives great insight into how Socket.IO works. Take the time to understand how this example works. If you understand this, adding more features (usernames, rooms, typing indicators, etc.) becomes much easier.&lt;br /&gt;
&lt;br /&gt;
=== The Chat Server ===&lt;br /&gt;
&lt;br /&gt;
Create a file named ''chat-server.js'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
import { createServer } from &amp;quot;node:http&amp;quot;;&lt;br /&gt;
import { readFile } from &amp;quot;node:fs/promises&amp;quot;;&lt;br /&gt;
import { Server } from &amp;quot;socket.io&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
const port = 3456;&lt;br /&gt;
const file = &amp;quot;client.html&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
/*&lt;br /&gt;
  Mini static server:&lt;br /&gt;
  - serves ONLY client.html for any request&lt;br /&gt;
  - Socket.IO also exposes a client bundle at /socket.io/socket.io.js&lt;br /&gt;
*/&lt;br /&gt;
const httpServer = createServer(async (req, res) =&amp;gt; {&lt;br /&gt;
  try {&lt;br /&gt;
    const data = await readFile(file);&lt;br /&gt;
    res.writeHead(200, { &amp;quot;Content-Type&amp;quot;: &amp;quot;text/html&amp;quot; });&lt;br /&gt;
    res.end(data);&lt;br /&gt;
  } catch (err) {&lt;br /&gt;
    res.writeHead(500, { &amp;quot;Content-Type&amp;quot;: &amp;quot;text/plain&amp;quot; });&lt;br /&gt;
    res.end(&amp;quot;Server error: could not read client.html&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
// Attach Socket.IO to the HTTP server:&lt;br /&gt;
const io = new Server(httpServer);&lt;br /&gt;
&lt;br /&gt;
io.on(&amp;quot;connection&amp;quot;, (socket) =&amp;gt; {&lt;br /&gt;
  // Runs when a new Socket.IO connection is established&lt;br /&gt;
  console.log(&amp;quot;New connection:&amp;quot;, socket.id);&lt;br /&gt;
&lt;br /&gt;
  socket.on(&amp;quot;message_to_server&amp;quot;, (data) =&amp;gt; {&lt;br /&gt;
    // Runs when the server receives a new message from a client&lt;br /&gt;
    console.log(&amp;quot;message:&amp;quot;, data.message);&lt;br /&gt;
&lt;br /&gt;
    // Send to everyone (including the sender):&lt;br /&gt;
    io.emit(&amp;quot;message_to_client&amp;quot;, { message: data.message });&lt;br /&gt;
&lt;br /&gt;
    // If you wanted: send to everyone EXCEPT the sender:&lt;br /&gt;
    // socket.broadcast.emit(&amp;quot;message_to_client&amp;quot;, { message: data.message });&lt;br /&gt;
  });&lt;br /&gt;
});&lt;br /&gt;
&lt;br /&gt;
httpServer.listen(port, () =&amp;gt; {&lt;br /&gt;
  console.log(`Server running at http://localhost:${port}/`);&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What this server does:&lt;br /&gt;
&lt;br /&gt;
* Creates a basic HTTP server that serves a single file, ''client.html''.&lt;br /&gt;
* Attaches a Socket.IO server to that HTTP server.&lt;br /&gt;
* Listens for a client event called ''message_to_server''.&lt;br /&gt;
* When a message arrives, it broadcasts a ''message_to_client'' event to connected clients.&lt;br /&gt;
&lt;br /&gt;
'''Important note:''' By default, the Socket.IO server exposes a browser client bundle at '''/socket.io/socket.io.js''' which we use from the HTML page. :contentReference[oaicite:3]{index=3}&lt;br /&gt;
&lt;br /&gt;
=== The Chat Client ===&lt;br /&gt;
&lt;br /&gt;
Create ''client.html'':&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;html4strict&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE html&amp;gt;&lt;br /&gt;
&amp;lt;html&amp;gt;&lt;br /&gt;
  &amp;lt;head&amp;gt;&lt;br /&gt;
    &amp;lt;meta charset=&amp;quot;utf-8&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;title&amp;gt;Socket.IO Chat Demo&amp;lt;/title&amp;gt;&lt;br /&gt;
  &amp;lt;/head&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &amp;lt;body&amp;gt;&lt;br /&gt;
    &amp;lt;input type=&amp;quot;text&amp;quot; id=&amp;quot;message_input&amp;quot; /&amp;gt;&lt;br /&gt;
    &amp;lt;button id=&amp;quot;send_btn&amp;quot;&amp;gt;send&amp;lt;/button&amp;gt;&lt;br /&gt;
    &amp;lt;div id=&amp;quot;chatlog&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    &amp;lt;script src=&amp;quot;/socket.io/socket.io.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;
    &amp;lt;script&amp;gt;&lt;br /&gt;
      const socket = io(); // connects back to the same host/port&lt;br /&gt;
&lt;br /&gt;
      socket.on(&amp;quot;message_to_client&amp;quot;, (data) =&amp;gt; {&lt;br /&gt;
        // Append an HR and then the message as text (safe against XSS)&lt;br /&gt;
        const chatlog = document.getElementById(&amp;quot;chatlog&amp;quot;);&lt;br /&gt;
        chatlog.appendChild(document.createElement(&amp;quot;hr&amp;quot;));&lt;br /&gt;
        chatlog.appendChild(document.createTextNode(data.message));&lt;br /&gt;
      });&lt;br /&gt;
&lt;br /&gt;
      function sendMessage() {&lt;br /&gt;
        const input = document.getElementById(&amp;quot;message_input&amp;quot;);&lt;br /&gt;
        const msg = input.value;&lt;br /&gt;
        socket.emit(&amp;quot;message_to_server&amp;quot;, { message: msg });&lt;br /&gt;
        input.value = &amp;quot;&amp;quot;;&lt;br /&gt;
        input.focus();&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
      document.getElementById(&amp;quot;send_btn&amp;quot;).addEventListener(&amp;quot;click&amp;quot;, sendMessage);&lt;br /&gt;
&lt;br /&gt;
      // Optional: press Enter to send&lt;br /&gt;
      document.getElementById(&amp;quot;message_input&amp;quot;).addEventListener(&amp;quot;keydown&amp;quot;, (e) =&amp;gt; {&lt;br /&gt;
        if (e.key === &amp;quot;Enter&amp;quot;) sendMessage();&lt;br /&gt;
      });&lt;br /&gt;
    &amp;lt;/script&amp;gt;&lt;br /&gt;
  &amp;lt;/body&amp;gt;&lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Note:''' This example sends an object ({message: ...}) as the event data, but you can send any JavaScript datatype, including numbers, strings, arrays, and object literals.&lt;br /&gt;
&lt;br /&gt;
Also notice that we display messages using createTextNode(), which treats content as plain text (helpful to avoid XSS when printing user-generated input).&lt;br /&gt;
&lt;br /&gt;
=== Running the Example ===&lt;br /&gt;
&lt;br /&gt;
Save ''chat-server.js'' and ''client.html'' in the same directory, then:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ node chat-server.js&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Open your browser to:&lt;br /&gt;
&lt;br /&gt;
http://localhost:3456/&lt;br /&gt;
&lt;br /&gt;
Open the page in two windows (or two different browsers). Now type messages — you have a (very basic) chat client!&lt;br /&gt;
&lt;br /&gt;
== Broadcasting: &amp;quot;everyone&amp;quot; vs &amp;quot;everyone else&amp;quot; ==&lt;br /&gt;
&lt;br /&gt;
Socket.IO gives you multiple ways to send events:&lt;br /&gt;
&lt;br /&gt;
* '''io.emit(...)''' sends to everyone connected (including the sender).&lt;br /&gt;
* '''socket.broadcast.emit(...)''' sends to everyone except the sender.&lt;br /&gt;
* '''io.to(room).emit(...)''' sends only to sockets in a specific room (see below).&lt;br /&gt;
&lt;br /&gt;
Broadcasting is a server-side feature. :contentReference[oaicite:4]{index=4}&lt;br /&gt;
&lt;br /&gt;
== Rooms (and why you care) ==&lt;br /&gt;
&lt;br /&gt;
Rooms are a server-only concept that let you group sockets together so you can broadcast to a subset of clients (for example: one chat room per group). :contentReference[oaicite:5]{index=5}&lt;br /&gt;
&lt;br /&gt;
Basic idea:&lt;br /&gt;
&lt;br /&gt;
* A socket can join and leave rooms.&lt;br /&gt;
* You can emit to everyone in a room.&lt;br /&gt;
&lt;br /&gt;
Example (server-side):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;javascript&amp;quot;&amp;gt;&lt;br /&gt;
io.on(&amp;quot;connection&amp;quot;, (socket) =&amp;gt; {&lt;br /&gt;
  socket.on(&amp;quot;join_room&amp;quot;, (data) =&amp;gt; {&lt;br /&gt;
    socket.join(data.room);&lt;br /&gt;
  });&lt;br /&gt;
&lt;br /&gt;
  socket.on(&amp;quot;room_message&amp;quot;, (data) =&amp;gt; {&lt;br /&gt;
    // send only to people in that room&lt;br /&gt;
    io.to(data.room).emit(&amp;quot;message_to_client&amp;quot;, { message: data.message });&lt;br /&gt;
  });&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Rooms make it much easier to build:&lt;br /&gt;
* group chats&lt;br /&gt;
* team-based games&lt;br /&gt;
* collaborative apps with separate workspaces&lt;br /&gt;
&lt;br /&gt;
== Resources ==&lt;br /&gt;
&lt;br /&gt;
* Socket.IO documentation (v4): https://socket.io/docs/v4/ :contentReference[oaicite:6]{index=6}&lt;br /&gt;
* Server installation: https://socket.io/docs/v4/server-installation/ :contentReference[oaicite:7]{index=7}&lt;br /&gt;
* Client installation (including /socket.io/socket.io.js): https://socket.io/docs/v4/client-installation/ :contentReference[oaicite:8]{index=8}&lt;br /&gt;
* Rooms: https://socket.io/docs/v4/rooms/ :contentReference[oaicite:9]{index=9}&lt;br /&gt;
&lt;br /&gt;
[[Category:Module 7]]&lt;/div&gt;</summary>
		<author><name>Todd</name></author>
		
	</entry>
</feed>