networking and data access with eqela

Download Networking and Data Access with Eqela

If you can't read please download the document

Upload: jobandesther

Post on 22-Jun-2015

1.247 views

Category:

Technology


1 download

TRANSCRIPT

  • 1. Copyright 2012 Job and Esther Technologies, Inc.

2. Copyright 2012 Job and Esther Technologies, Inc.(3) NETWORKING ANDDATA ACCESS 3. Copyright 2012 Job and Esther Technologies, Inc.NETWORK PROGRAMMING (eq.net) 4. Copyright 2012 Job and Esther Technologies, Inc.eq.net.TCPSocketIn Eqela, TCP/IP sockets are implemented througheq.net.TCPSocketvar socket = TCPSocket.create("192.168.1.1", 80);// read and write to the socketsocket.close(); 5. Copyright 2012 Job and Esther Technologies, Inc.Domain Name System (DNS) There are two ways to convert a host name into anIP address:1.Using eq.net.DNSCacheExample:1.Using eq.net.DNSResolverExample:orvar ip = DNSCache.resolve(hostname);var ip = DNSResolver.get_ip_address(hostname);var ip_coll = DNSResolver.get_ip_addresses(hostname); 6. Copyright 2012 Job and Esther Technologies, Inc.Sequence of connecting a clientsocket via TCP/IP Regardless of the operating system andprogramming language, the process of connectinga TCP/IP socket is as follows:1.Create a socket / socket object2.Resolve the server hostname into an IP address usingDNS3.Establish a TCP connection to the destination host /port4.Read & write data 7. Copyright 2012 Job and Esther Technologies, Inc.Sample socket client programclass Main : Command{public int main(Collection args) {var addr = args.get_index(0) as String;Log.message("resolve %s ..".printf().add(addr));var ip = DNSCache.resolve(addr);if(ip == null) {Log.error("failed to resolve");return(1);}Log.message("connect to %s ..".printf().add(ip));var os = OutputStream.create(TCPSocket.create(ip, 80));if(os == null) {Log.error.("failed to connect");return(1);}Log.message("sending data ..");os.write_string("hello");Log.message("done");return(0);}} 8. Copyright 2012 Job and Esther Technologies, Inc.Threading and networkingIn GUI applications, you are either not allowed, or itis not recommended, to do networking in the samethread as the GUI- This would freeze the user interface -In GUI applications, networking should generally bedone in separate threads 9. Copyright 2012 Job and Esther Technologies, Inc.Network threading in Eqelaclass MyNetworkTask : Task {public Object run(EventReceiver listener) {var socket = TCPSocket.create(64.79.194.207, 80);if(socket != null) {return(Connected);}return(Failed);}}class Main : AlignWidget, EventReceiver {LabelWidget status;public void initialize() {base.initialize();add(status = LabelWidget.for_string(Ready));}public void start() {base.start();status.set_text(Processing ..);Task.execute(new MyNetworkTask(), this);}public void on_event(Object o) {status.set_text(o as String);}} 10. Copyright 2012 Job and Esther Technologies, Inc.Android: PermissionsTo use certain platform features on the Androidplatform, the application must declare thepermissions it requiresSpecifically, Internet access requires permissionsPermissions can be declared in the Eqela applicationconfig file (.config)android_manifest_permissions: android.permission.INTERNET 11. Copyright 2012 Job and Esther Technologies, Inc.Availability of TCP/IP socketsAlmost all modern operating systems / software platformsallow the use of TCP/IP sockets .... with the notable exception of the HTML5 platformEqela does not currently support TCP/IP sockets in HTML5applications (only HTTP is available)Legacy platforms (such as J2ME) may also not support TCPsocketsTo maximize compatibility, use of HTTP networking isrecommended in applications 12. Copyright 2012 Job and Esther Technologies, Inc.Sequence of establishing a TCP/IPserver socket Regardless of the operating system andprogramming language used, the sequence is thesame:1.Create a socket / socket object2.Bind the socket to a specific port (choose a specificport number)3.Start listening for incoming connections on thesocket4.Accept connections as they come in 13. Copyright 2012 Job and Esther Technologies, Inc.Sample server programclass Main : Command{public int main(Collection args) {var s = TCPSocket.create();if(s.listen(1503) == false) {Log.error("Failed to listen");return(1);}TCPSocket c;Log.message("waiting on port 1503 ..");while((c = s.accept()) != null) {Log.message("received a connection");Log.message("received: %s".printf().add(InputStream.create(c).read_all_string()));}return(0);}} 14. Copyright 2012 Job and Esther Technologies, Inc.User Datagram Protocol (UDP)UDP socket is implemented througheq.net.UDPSocketvar socket = UDPSocket.create(); 15. Copyright 2012 Job and Esther Technologies, Inc.User Datagram Protocol (UDP)socket.send("This is data to send".to_utf8_buffer(false), "192.168.1.1", 1503);if(socket.bind(1503) == false) {Log.error("Failed to bind to UDP port 1503");}var buf = DynamicBuffer.create(8192);if(socket.receive(buf, 1000000) > 0) {// data was received}A call to bind() can be made to choose aspecific port number. If none is bound, then aport is chosen automaticallyTo send and receive data, use the send() andreceive() methods 16. Copyright 2012 Job and Esther Technologies, Inc.HTTP clientEqela also provides an implementation of an HTTPclient, which enables Eqela applications to easilyretrieve web data over the HTTP protocol.The HTTP API can be called either in a backgroundthread, or in the current thread, depending on therequirement.The HTTP API will receive an object of typeeq.net.HTTPRequest, and will return an object oftype eq.net.HTTPResponse. 17. Copyright 2012 Job and Esther Technologies, Inc.Uniform Resource Locator (URL) URL is the global address of documents and otherresources on the World Wide Web A URL may consist of some of the followingcomponents: Scheme name, host name, port number, path, querystring and fragment identifierThe syntax is:scheme://host:port/path?query_string#fragment_id 18. Copyright 2012 Job and Esther Technologies, Inc.Uniform Resource Locator (URL)Uniform Resource Locator is implemented througheq.net.URLvar url = URL.for_string(str); 19. Copyright 2012 Job and Esther Technologies, Inc.Constructing an HTTPRequestvar query = HTTPRequest.create().set_method("GET").set_url(URL.for_string("http://www.eqela.com")));var query = HTTPRequest.GET("http://www.eqela.com");The HTTPRequest class is very flexible, and allaspects of the query can be configured,including HTTP headers and cookies. 20. Copyright 2012 Job and Esther Technologies, Inc.Using the HTTPClientOnce the query is constructed, it can be executedthrough eq.net.HTTPClient// Execute the query synchronouslyvar response = HTTPClient.get_response(query);// Execute the query asynchronously:HTTPClient.query(query, listener);// The second parameter supplies a listener object of type// eq.api.EventReceiver that will be notified of the// query progress and the final result. 21. Copyright 2012 Job and Esther Technologies, Inc.HTTP client listenerThe listener could be implemented as follows:class MyListener : EventReceiver{public void on_event(Object o) {if(o == null) {// request failed}else if(o is HTTPResponse) {// response was received}}} 22. Copyright 2012 Job and Esther Technologies, Inc.Higher level protocolsEqela offers some convenience implementations ofhigher level protocols:eq.web.rss RSS news aggregationeq.web.smtp Sending email via SMTP 23. Copyright 2012 Job and Esther Technologies, Inc.DATA ACCESS (eq.data) 24. Copyright 2012 Job and Esther Technologies, Inc.The eq.data APIThe eq.data module provides an easy-to-use objectoriented database / data management APIThe following are the main classes and interfaces:DatabaseTableIteratorWrapperSqlDatabaseSqlStatement 25. Copyright 2012 Job and Esther Technologies, Inc.Local database access// open a database, creating it if necessaryvar f = File.for_native_path(C:mydatabase.db);var db = SqlDatabase.for_file(f);if(db == null) {// db does not existdb = SqlDatabase.create_file(f);if(db != null) {db.execute(db.prepare(CREATE TABLE test ( id INTEGER, text TEXT );));}} Different backend implementations per each platform. Currently allimplementations are based on Sqlite Currently not available for HTML5 builds 26. Copyright 2012 Job and Esther Technologies, Inc.Databases: Convenience APIvar db = new Database();db.add_table(Table.for_name(users).set_index(username));db.add_table(Table.for_name(sessions));if(db.open(File.for_native_path(C:mydatabase.db)) == false){// FAILED}foreach(PropertyObject record in db.query_all(users)) {// process the record} Utilizes the SqlDatabase API for actual functionality Automatically creates tables, generates queries and other SQL statements 27. Copyright 2012 Job and Esther Technologies, Inc.SqlDatabase: Other databasesA database driver for any SQL database can beintegrated by creating a new class that implementsSqlDatabaseThird party native drivers can be integrated byembedding calls to the third party driver API(Oracle, MS SQL, MySQL, ..) 28. Copyright 2012 Job and Esther Technologies, Inc.Connecting to databases from mobile devices: Whatkind of considerations does this involve? 29. Copyright 2012 Job and Esther Technologies, Inc.Direct connectivityDirect connectivity : A mobile device connectsstraight to the database server, and executes SQLinstructions on it+ A very straightforward concept- Security concerns- Possible connectivity issues- Lack of database drivers for mobile devices 30. Copyright 2012 Job and Esther Technologies, Inc.Connectivity via gatewayAn intermediate server / service that handles themobile devices requests, and communicates directlywith the database. Best implemented using HTTP+ No need to expose database server to the Internet+ HTTP connectivity is universal+ No need for database drivers (HTTPClient will do)- Must set up a gateway service 31. Copyright 2012 Job and Esther Technologies, Inc.Thank you