Last active
May 21, 2016 22:49
-
-
Save lourd/a49f014820501369497cf46849564ced to your computer and use it in GitHub Desktop.
Simple Node http server and client communication example
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
// Bring in the core HTTP module | |
var http = require('http') | |
///////////////////////// | |
// Server code | |
///////////////////////// | |
// The in-memory state. Will be reset every time the server restarts! | |
var state = 'OFF' | |
// This function runs whenever the server gets a new message | |
function messageHandler(request, response) { | |
console.log('Message received!') | |
// If it's a post method, if the button is being pressed | |
if (request.method == 'POST') { | |
var message = '' | |
request.on('data', function (data) { | |
message += data | |
}) | |
request.on('end', function () { | |
// Update the state | |
if ( message == 'ON' ) { | |
state = 'ON' | |
} else if ( message == 'OFF' ) { | |
state = 'OFF' | |
} else { | |
console.log('Received unrecognized message', message) | |
} | |
}) | |
} | |
// If it's a GET request, return the state | |
if ( request.method == 'GET' ) { | |
response.end(state) | |
} | |
} | |
// Create the http server instance | |
var server = http.createServer(messageHandler) | |
// Starts the server | |
server.listen(3000, function () { | |
console.log('Server listening on port 3000') | |
}) | |
///////////////////////// | |
// Client code | |
///////////////////////// | |
// Sends an http request | |
function sendAMessage() { | |
// The options for the message | |
var options = { | |
method: 'POST', | |
hostname: 'localhost', | |
port: 3000, | |
} | |
// Creates the http request instance | |
var request = http.request(options) | |
// Randomly decide whether we're saying on or off | |
var message = Math.random() > 0.5 ? 'ON' : 'OFF' | |
console.log('Sending a message...', message) | |
// Send the message | |
request.write(message) // The actual message content | |
// Close the request | |
request.end() | |
} | |
// Send a message every 3 seconds | |
setInterval(sendAMessage, 3 * 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment