Created
July 24, 2015 03:13
-
-
Save rocky/10f4fd5c410ab2f1845f to your computer and use it in GitHub Desktop.
Simple websocket code in nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| sudo npm install -g websocket |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env node | |
| var WebSocketClient = require('websocket').client; | |
| var client = new WebSocketClient(); | |
| client.on('connectFailed', function(error) { | |
| console.log('Connect Error: ' + error.toString()); | |
| }); | |
| client.on('connect', function(connection) { | |
| console.log('WebSocket Client Connected'); | |
| connection.on('error', function(error) { | |
| console.log("Connection Error: " + error.toString()); | |
| }); | |
| connection.on('close', function() { | |
| console.log('echo-protocol Connection Closed'); | |
| }); | |
| connection.on('message', function(message) { | |
| if (message.type === 'utf8') { | |
| console.log("Received: '" + message.utf8Data + "'"); | |
| } | |
| }); | |
| function sendNumber() { | |
| if (connection.connected) { | |
| var number = Math.round(Math.random() * 0xFFFFFF); | |
| connection.sendUTF(number.toString()); | |
| setTimeout(sendNumber, 1000); | |
| } | |
| } | |
| sendNumber(); | |
| }); | |
| client.connect('ws://localhost:27001/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment