DataInputStreams – More On Why Vala Is Awesome!
Vala makes it incredibly easy to access resources from online.
Imagine you would like to access some information from a website. For me, I wanted to download magnetic declination from the NOAA website. I wanted to be able to lookup mag. dec. from a given latitude and longitude. My programming experience has mostly been with C++ (although I’ve done a bit of Python etc), and in C++ accessing the internet is no trivial task. You either need to find some library that will do it for you (libcurl comes to mind) or do it hardcore with sockets.
Vala, on the other hand, will access HTTP resources just as easily as it will access files from your hard drive. Just look at this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
async void read_mag_var_async (File file) { try { var dis = new DataInputStream (file.read ()); string line = null; while ((line = yield dis.read_line_async (Priority.DEFAULT)) != null) { //could just use string.scanf here, but this is safer. var tok = new Tokeniser(line, ','); //this is just a Vala version of the etk::Tokeniser char buf[20]; var counter = 0; while(tok.next((char*)buf, 20)) { if(buf[0] == '#') //ignore lines that start with '#', they are comments break; if(counter == 4) //the fifth token (counter starts at 0) is magnetic declination { mag_var_spin.set_value(double.parse((string)buf)); //update UI inst_setting_changed_counter = 8; //reset countdown to upload inst settings } counter++; } } } catch (Error e) { error (e.message); } } private void calc_mag_var_clicked() { //build the URI var now = new DateTime.now_local(); string uri = "http://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination?"; uri += "resultFormat=csv&"; uri += "startMonth="; uri += now.get_month().to_string(); uri += "&lat1="; uri += port.home_latitude.to_string(); uri += "&lon1="; uri += port.home_longitude.to_string(); //make a file object from the URI var file = File.new_for_uri (uri); //i think this spawns a new thread which reads the file? read_mag_var_async(file); } |
That is crazy simple! Two small functions, and I can pull information straight off the internet and plug it into my desktop GUI. All the NodeJS losers are laughing at me right now, but I’m an old skool C plus pluser and I’m inpressed.