This connects to a node js server and returns the following
successfully connected
HTTP/1.1 200 OK
access-control-allow-origin: *
content-type: text/plain
content-length: 59
date: Sun, 17 May 2015 01:41:11 GMT
Thank You For The Cross-Domain AJAX Request:
Method: GET
.
The .ino file is
…
TCPClient client;
char server[] = "my-server-url.com";
bool myUsbSerialDebugOn = true; // set to false when not hooked up to USB
int connectToMyServer(String myNothing) {
digitalWrite(D7, HIGH);
if (client.connect(server, 80)) {
client.write("GET / HTTP/1.1\r\n");
client.write("Host: my-server-url.com\r\n");
client.write("\r\n");
digitalWrite(D7, LOW);
if (myUsbSerialDebugOn){
Serial.println("successfully connected");
}
return 1; // successfully connected
} else {
digitalWrite(D7, LOW);
if (myUsbSerialDebugOn){
Serial.println("failed to connect");
}
return -1; // failed to connect
}
}
void setup() {
pinMode(D7, OUTPUT);
Spark.function("connect", connectToMyServer);
digitalWrite(D7, HIGH);
delay(25000);
digitalWrite(D7, LOW);
if (myUsbSerialDebugOn){
Serial.begin(9600); // Initalize the USB Serial port
while(!Serial.available()) SPARK_WLAN_Loop();
Serial.println("Hello Computer");
}
}
void loop() {
digitalWrite(D7, LOW);
if (client.connected()) {
if (client.available()) {
digitalWrite(D7, HIGH);
char myIncoming = client.read();
if (myUsbSerialDebugOn){
Serial.print(myIncoming);
// delay(2);
}
} else {
//digitalWrite(D7, LOW);
}
}
}
…
The Node js file is
// Include our HTTP module.
var http = require( "http" );
// Create an HTTP server so that we can listen for, and respond to
// incoming HTTP requests. This requires a callback that can be used
// to handle each incoming request.
var server = http.createServer(
function( request, response ){
// When dealing with CORS (Cross-Origin Resource Sharing)
// requests, the client should pass-through its origin (the
// requesting domain). We should either echo that or use *
// if the origin was not passed.
var origin = (request.headers.origin || "*");
// Check to see if this is a security check by the browser to
// test the availability of the API for the client. If the
// method is OPTIONS, the browser is check to see to see what
// HTTP methods (and properties) have been granted to the
// client.
if (request.method.toUpperCase() === "OPTIONS"){
// Echo back the Origin (calling domain) so that the
// client is granted access to make subsequent requests
// to the API.
response.writeHead(
"204",
"No Content",
{
"access-control-allow-origin": origin,
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
"access-control-allow-headers": "content-type, accept",
"access-control-max-age": 10, // Seconds.
"content-length": 0
}
);
// End the response - we're not sending back any content.
return( response.end() );
}
// -------------------------------------------------- //
// -------------------------------------------------- //
// If we've gotten this far then the incoming request is for
// our API. For this demo, we'll simply be grabbing the
// request body and echoing it back to the client.
// Create a variable to hold our incoming body. It may be
// sent in chunks, so we'll need to build it up and then
// use it once the request has been closed.
var requestBodyBuffer = [];
// Now, bind do the data chunks of the request. Since we are
// in an event-loop (JavaScript), we can be confident that
// none of these events have fired yet (??I think??).
request.on(
"data",
function( chunk ){
// Build up our buffer. This chunk of data has
// already been decoded and turned into a string.
requestBodyBuffer.push( chunk );
}
);
// Once all of the request data has been posted to the
// server, the request triggers an End event. At this point,
// we'll know that our body buffer is full.
request.on(
"end",
function(){
// Flatten our body buffer to get the request content.
var requestBody = requestBodyBuffer.join( "" );
// Create a response body to echo back the incoming
// request.
var responseBody = (
"Thank You For The Cross-Domain AJAX Request:\n\n" +
"Method: " + request.method + "\n\n" +
requestBody
);
// Send the headers back. Notice that even though we
// had our OPTIONS request at the top, we still need
// echo back the ORIGIN in order for the request to
// be processed on the client.
response.writeHead(
"200",
"OK",
{
"access-control-allow-origin": origin,
"content-type": "text/plain",
"content-length": responseBody.length
}
);
// Close out the response.
return( response.end( responseBody ) );
}
);
}
);
// Bind the server to port 8080.
server.listen( process.env.PORT, process.env.IP );
// Debugging:
console.log( "Node.js listening on port " + process.env.PORT);
…
Here is another socket node js server that sends back something interesting
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(Number(process.env.PORT),process.env.IP);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
// Create periodical which ends a message to the client every 5 seconds
var interval = setInterval(function() {
client.send('This is a message from the server! ' + new Date().getTime());
},5000);
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
…
The output on the Spark Core looks like
successfully connected
HTTP/1.1 200 OK
content-type: text/html
date: Sun, 17 May 2015 04:15:29 GMT
transfer-encoding: chunked
1c
<h1>Hello Socket Lover!</h1>
0