Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple Socket.io test with client and server (Node.js) parts.
{
"name": "test-socket-io",
"version": "1.0.0",
"description": "Simple Socket.io client and server test",
"main": "test-io-server.js",
"dependencies": {
"socket.io": "^1.5.0"
},
"author": "Cliff Hall",
"license": "MIT",
"homepage": "http://cliffordhall.com"
}
<!-- test-io-client.html -->
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
function init()
{
output = document.getElementById("output");
testSocket();
}
function testSocket()
{
var socket = io.connect('http://localhost:3000/');
socket.on('test', onMessage );
socket.on('connect', onConnect );
socket.on('disconnect', onDisconnect );
socket.on('connect_error', onError );
socket.on('reconnect_error', onError );
function onConnect(evt)
{
writeToScreen("CONNECTED");
doSend("Allo?");
}
function onDisconnect(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(data)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + data+'</span>');
socket.close();
}
function onError(message)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + message);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
socket.emit('test', message);
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
}
window.addEventListener("load", init, false);
</script>
<h2>Socket.io Test</h2>
<div id="output"></div>
// test-io-server.js
// Create the socket server
const PORT = 3000;
var socket = require('socket.io')(PORT);
socket.on('connection', function(client) {
// Listen for test and disconnect events
client.on('test', onTest);
client.on('disconnect', onDisconnect);
// Handle a test event from the client
function onTest(data) {
console.log('Received: "' + data + '" from client: ' + client.id);
client.emit('test', "Cheers, " + client.id);
}
// Handle a disconnection from the client
function onDisconnect() {
console.log('Received: disconnect event from client: ' + client.id);
client.removeListener('test', onTest);
client.removeListener('disconnect', onDisconnect);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment