Skip to content

Instantly share code, notes, and snippets.

@janusnic
Forked from cliffhall/a-simple-socket-io-test.md
Created October 21, 2016 10:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save janusnic/90fcadaf0ad5766f7afb6104e6275caa to your computer and use it in GitHub Desktop.
Save janusnic/90fcadaf0ad5766f7afb6104e6275caa to your computer and use it in GitHub Desktop.
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": "https://github.com/cliffhall/"
}
<!-- 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);
}
});
@divyamohanraju07
Copy link

I tried ur sample i get "ERROR: Error: xhr poll error"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment