SlideShare a Scribd company logo
1 of 13
Download to read offline
How do I?
In this short video I’ll cover some core concepts of networking and webservices on mobile devices and Codename One



First and most importantly for those of you coming from the desktop or server world, this might not be a shock that network on mobile devices is unreliable. However, the
extent of this is sometimes surprising to developers who are new to mobile. That’s why many low level networking strategies are discouraged on mobile devices.

Another big surprise for developers is that Apple literally blocks HTTP on their devices unless you have a really good excuse. If you will try to connect to HTTP from an
app that doesn’t explicitly enable that the connection will just fail. You need to use HTTPS or ask for a special permission, notice that if you ask for that permission and
don’t have a good enough reason your app will be rejected from the appstore.

Sockets are usable on mobile devices but they are flaky and hard to use across NATs and devices. We only got server sockets working reliably on Android, they are
possible on iOS but they are pretty different there.

As a solution of sort to some of those issues websockets have risen in recent years and are shaping up to be a very interesting midrange option.
Use Networking & WebServices
In this short video I’ll cover some core concepts of networking and webservices on mobile devices and Codename One



First and most importantly for those of you coming from the desktop or server world, this might not be a shock that network on mobile devices is unreliable. However, the
extent of this is sometimes surprising to developers who are new to mobile. That’s why many low level networking strategies are discouraged on mobile devices.

Another big surprise for developers is that Apple literally blocks HTTP on their devices unless you have a really good excuse. If you will try to connect to HTTP from an
app that doesn’t explicitly enable that the connection will just fail. You need to use HTTPS or ask for a special permission, notice that if you ask for that permission and
don’t have a good enough reason your app will be rejected from the appstore.

Sockets are usable on mobile devices but they are flaky and hard to use across NATs and devices. We only got server sockets working reliably on Android, they are
possible on iOS but they are pretty different there.

As a solution of sort to some of those issues websockets have risen in recent years and are shaping up to be a very interesting midrange option.
Mobile Is Different
✦Network is unreliable
✦iOS Prohibits HTTP and insecure communication
✦Sockets are possible but might be unreliable
✦Server sockets are difficult and less portable
✦WebSockets are rising
In this short video I’ll cover some core concepts of networking and webservices on mobile devices and Codename One



First and most importantly for those of you coming from the desktop or server world, this might not be a shock that network on mobile devices is unreliable. However, the
extent of this is sometimes surprising to developers who are new to mobile. That’s why many low level networking strategies are discouraged on mobile devices.

Another big surprise for developers is that Apple literally blocks HTTP on their devices unless you have a really good excuse. If you will try to connect to HTTP from an
app that doesn’t explicitly enable that the connection will just fail. You need to use HTTPS or ask for a special permission, notice that if you ask for that permission and
don’t have a good enough reason your app will be rejected from the appstore.

Sockets are usable on mobile devices but they are flaky and hard to use across NATs and devices. We only got server sockets working reliably on Android, they are
possible on iOS but they are pretty different there.

As a solution of sort to some of those issues websockets have risen in recent years and are shaping up to be a very interesting midrange option.
ConnectionRequest URL Socket WebSocket
Builtin Builtin
2 implementations
builtin & cn1lib
cn1lib
Modeled on JavaScript
async networking model
Modeled on java.net.URL
Builtin - async API
cn1lib - low level stream API
Low level callback API
Threaded Seamlessly Manual threading
Builtin - seamless threading
cn1lib - manual threading
Threaded Seamlessly
Synchronous &
asynchronous API’s
Synchronous API
Builtin - asynchronous
cn1lib - synchronous
Asynchronous
Highly Portable Portable
Builtin - iOS/Android
cn1lib - portable but low
level
Portable
Secured thru HTTPS Secured thru HTTPS Insecure Secured thru SSL
4 Network Options
The most common networking API in Codename One is Connection request which is paired with the network manager. It’s inspired by JavaScripts asynchronous
networking but tries to provide more low level control. The connection request API was developed with a goal of extreme portability and best practices built-in. It’s
seamlessly threaded and can automatically work with the EDT as a synchronous or asynchronous API.

We also have some support for the URL class which helps port Java SE code to Codename One. It doesn’t use the network manager API and goes directly to the low
level API’s. As a result you need to take care of threads yourself and might need to work thru some low level differences in behavior between platforms.

We have two socket implementations, one is builtin to Codename One and works asynchronously thru a callback. The other was implemented as a cn1lib and is a lower
level API that works directly with the streams. Sockets are inherently very low level and are an advanced API to use.

Web sockets serve as a middle of the road approach. They are implemented as a cn1lib as well but use a simplified asynchronous callback API. Since common servers
already support websockets, the server side should be a breeze. They are relatively easy to work with and allow sending messages back and forth from the server.
Connection Request
ConnectionRequest c = new ConnectionRequest(url, false);
addToQueue(c);
import static com.codename1.ui.CN.*;
Before we go to the code notice that in order to use this code you will need to import the CN class statics. 

Creating a hello world get request is as simple as adding a new connection request to the queue. Notice that the second argument indicates that we are making a GET
request and not a POST request which is the default. Also notice that the request is asynchronous so it might not have completed after the addToQueue call. So how do
we get the actual data from the URL?
3 Options
c.addResponseListener(e -> {
byte[] response = e.getConnectionRequest().getResponseData();
// do something with the response data
});
ConnectionRequest c = new ConnectionRequest(url, false) {
@Override
protected void readResponse(InputStream input) throws IOException {
// read input stream
}
};
addToQueueAndWait(c);
byte[] response = c.getResponseData();
// do something with the response data
There are 3 options…

First we can override read response and read the stream directly. This is arguably the best approach as we will only read the data once. Read response is invoked on the
network thread so make sure not to change the UI from that method! That is a good thing though as all your processing won’t block the event dispatch thread and won’t
slow the app noticeably.

The second option uses a response listener to get the result from the connection request. Notice that a response listener occurs on the event dispatch thread so this will
slow down execution slightly but you will be able to make changes to the UI directly so the code will be simpler.

The same is true about the last and arguably simplest option. When you use addToQueueAndWait instead of addToQueue the current thread is blocked using
invokeAndBlock and we can then extract the data. This is pretty convenient for simple requests and we use that often for those cases.
Builtin Sockets
Socket.connect(server, port, new SocketConnection() {
@Override
public void connectionError(int errorCode, String message) {
Log.p("Error connecting " + errorCode + ": " + message);
}
@Override
public void connectionEstablished(InputStream is, OutputStream os) {
while(connected) {
// read and write to input/output stream
}
}
});
The builtin sockets use an asynchronous API where the callback method is invoked once connection to the server is established. At that point you will have a thread with
two streams and you can just read or write from the streams as you see fit.
WebSockets
WebSocket sock = new WebSocket(websocketUrl) {
@Override
protected void onOpen() {
// we can start using the websocker
}
@Override
protected void onMessage(String string) {
// received string message from server
}
@Override
protected void onMessage(byte[] bytes) {
}
@Override
protected void onError(Exception excptn) {
Log.e(excptn);
}
};
sock.connect()
Web sockets are easier, you just receive messages and can send them using the web socket API. Notice that you shouldn’t send any message before onOpen was
invoked as you might fail badly… Web sockets are excellent for API’s like chat where a server might trigger a message to a device without the device making a request.
This is far more efficient than approaches such as polling which can result in serious battery drain and low performance.
URL
✦You can port code that uses java.net.URL to use
com.codename1.io.URL
✦You will need to handle threading on your own
✦There is no builtin support for events on the event
dispatch thread
✦You might inadvertently rely on low level platform
specific behaviors since URL is low level
I’ve mentioned URL before and indeed you can use the Codename One URL to port existing code but this also begs the question: why not use URL instead of
connection request?

Threading is hard would be the first and obvious answer. This is especially true on devices where QA needs to go far and wide

Connection request has some builtin capabilities that bind directly to the EDT for instance addToQueueAndWait, progress indicator etc.

URL is inherently less portable since it is low level and might expose platform behaviors that you don’t expect a common example is different redirection behavior on 302
for the various OS’s.
WebServices
✦WebService wizard can generate server client stubs
for remote method call over HTTP
✦ConnectionRequest can be used to invoke typical
restful webservices
✦Several cn1lib’s and builtin API’s exist to simplify
webservice calls e.g. com.codename1.io.rest.Rest
✦JSONParser & XMLParser support parsing common
formats the Result class supports XPath expressions
Webservices can be implemented in many ways in Codename One, a common approach is the webservice wizard detailed in the developer guide. It generates method
calls that map to server code and allow us to generate a remote function invocation on the server.

You can use connection request to invoke rest API’s from the client

You can use one of the 3rd party or builtin API’s to connect we have some great API’s such as the REST api that lets you invoke server code with almost no effort

You can use the builtin JSON and XML parsers as well as the Result class for xpath expression style parsing. You can also use some of the 3rd party parsers for JSON
and XML in the cn1lib section
Connection Request WebService
ConnectionRequest req = new ConnectionRequest(nextURL, false) {
@Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parser = new JSONParser();
Map response = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
items = (List)response.get("items");
nextURL = (String)response.get("nextPage");
}
@Override
protected void handleException(Exception err) {
Log.e(err);
}
};
addToQueueAndWait(req);
Here is a sample rest request from the kitchen sink, you will notice that there isn’t much here, we just parse the data and pass it on based on the response
Rest WebService
Response<Map> resultData = Rest.get(nextURL).
acceptJson().getAsJsonMap();
if(resultData.getResponseCode() != 200) {
Log.p("Error code from the server: " +
resultData.getResponseCode() + "n");
return;
}
items = (List)resultData.getResponseData().get("items");
nextURL = (String)resultData.getResponseData().get("nextPage");
We’ve ported that older kitchen sink code to use the new Rest API and this code is even easier. It removes the need for additional classes and can be chained to
generate a short expression.

We just get a result as a parsed map we can work with, which is very convenient. This API also has an asynchronous version which is similarly convenient
Thank You!
Thanks for watching, I hope you found this helpful

More Related Content

Similar to How do I - Networking and Webservices - Transcript.pdf

Raisa anthony web programming 1st week
Raisa anthony   web programming 1st weekRaisa anthony   web programming 1st week
Raisa anthony web programming 1st week
Raisa Anjani
 
SignalR Intro + WPDev
SignalR Intro + WPDevSignalR Intro + WPDev
SignalR Intro + WPDev
Sam Basu
 
netsuite-integration-whitepaper
netsuite-integration-whitepapernetsuite-integration-whitepaper
netsuite-integration-whitepaper
Olivier Gagnon
 
Nt1310 Final Exam Questions And Answers
Nt1310 Final Exam Questions And AnswersNt1310 Final Exam Questions And Answers
Nt1310 Final Exam Questions And Answers
Lisa Williams
 

Similar to How do I - Networking and Webservices - Transcript.pdf (20)

Raisa anthony web programming 1st week
Raisa anthony   web programming 1st weekRaisa anthony   web programming 1st week
Raisa anthony web programming 1st week
 
Ftp servlet
Ftp servletFtp servlet
Ftp servlet
 
video conference (peer to peer)
video conference (peer to peer)video conference (peer to peer)
video conference (peer to peer)
 
Stéphane Nicoll and Madhura Bhave at SpringOne Platform 2017
Stéphane Nicoll and Madhura Bhave at SpringOne Platform 2017Stéphane Nicoll and Madhura Bhave at SpringOne Platform 2017
Stéphane Nicoll and Madhura Bhave at SpringOne Platform 2017
 
Web Design World Flickr
Web Design World FlickrWeb Design World Flickr
Web Design World Flickr
 
SignalR Intro + WPDev
SignalR Intro + WPDevSignalR Intro + WPDev
SignalR Intro + WPDev
 
Web Application Troubleshooting Guide
Web Application Troubleshooting GuideWeb Application Troubleshooting Guide
Web Application Troubleshooting Guide
 
netsuite-integration-whitepaper
netsuite-integration-whitepapernetsuite-integration-whitepaper
netsuite-integration-whitepaper
 
Nt1310 Final Exam Questions And Answers
Nt1310 Final Exam Questions And AnswersNt1310 Final Exam Questions And Answers
Nt1310 Final Exam Questions And Answers
 
Food borne human diseases
Food borne human diseasesFood borne human diseases
Food borne human diseases
 
Spring Cloud Gateway - Nate Schutta
Spring Cloud Gateway - Nate SchuttaSpring Cloud Gateway - Nate Schutta
Spring Cloud Gateway - Nate Schutta
 
Prototyping Online Components(Part 02)_Internet of Things
Prototyping Online Components(Part 02)_Internet of ThingsPrototyping Online Components(Part 02)_Internet of Things
Prototyping Online Components(Part 02)_Internet of Things
 
Ethernet base divice control
Ethernet base divice controlEthernet base divice control
Ethernet base divice control
 
It and ej
It and ejIt and ej
It and ej
 
Lotusphere 2008 - Jumpstart 206 - Web Services Bootcamp
Lotusphere 2008 - Jumpstart 206 - Web Services BootcampLotusphere 2008 - Jumpstart 206 - Web Services Bootcamp
Lotusphere 2008 - Jumpstart 206 - Web Services Bootcamp
 
jmp206 - Lotus Domino Web Services Jumpstart
jmp206 - Lotus Domino Web Services Jumpstartjmp206 - Lotus Domino Web Services Jumpstart
jmp206 - Lotus Domino Web Services Jumpstart
 
Ajp notes-chapter-06
Ajp notes-chapter-06Ajp notes-chapter-06
Ajp notes-chapter-06
 
What are restful web services?
What are restful web services?What are restful web services?
What are restful web services?
 
Advanced Java Topics
Advanced Java TopicsAdvanced Java Topics
Advanced Java Topics
 
Web technology-guide
Web technology-guideWeb technology-guide
Web technology-guide
 

More from ShaiAlmog1

More from ShaiAlmog1 (20)

The Duck Teaches Learn to debug from the masters. Local to production- kill ...
The Duck Teaches  Learn to debug from the masters. Local to production- kill ...The Duck Teaches  Learn to debug from the masters. Local to production- kill ...
The Duck Teaches Learn to debug from the masters. Local to production- kill ...
 
create-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdfcreate-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdf
 
create-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdfcreate-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdf
 
create-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdfcreate-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdf
 
create-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdfcreate-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdf
 
create-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdfcreate-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdf
 
create-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdfcreate-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdf
 
create-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdfcreate-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdf
 
create-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdfcreate-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdf
 
create-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdfcreate-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdf
 
create-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdfcreate-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdf
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
 
create-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdfcreate-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdf
 
Creating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdfCreating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdf
 
Creating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdfCreating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdf
 
Creating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdfCreating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdf
 
Creating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdfCreating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdf
 
Creating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdfCreating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdf
 
Creating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdfCreating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdf
 
Creating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdfCreating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdf
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

How do I - Networking and Webservices - Transcript.pdf

  • 1. How do I? In this short video I’ll cover some core concepts of networking and webservices on mobile devices and Codename One
 
 First and most importantly for those of you coming from the desktop or server world, this might not be a shock that network on mobile devices is unreliable. However, the extent of this is sometimes surprising to developers who are new to mobile. That’s why many low level networking strategies are discouraged on mobile devices. Another big surprise for developers is that Apple literally blocks HTTP on their devices unless you have a really good excuse. If you will try to connect to HTTP from an app that doesn’t explicitly enable that the connection will just fail. You need to use HTTPS or ask for a special permission, notice that if you ask for that permission and don’t have a good enough reason your app will be rejected from the appstore. Sockets are usable on mobile devices but they are flaky and hard to use across NATs and devices. We only got server sockets working reliably on Android, they are possible on iOS but they are pretty different there.
 As a solution of sort to some of those issues websockets have risen in recent years and are shaping up to be a very interesting midrange option.
  • 2. Use Networking & WebServices In this short video I’ll cover some core concepts of networking and webservices on mobile devices and Codename One
 
 First and most importantly for those of you coming from the desktop or server world, this might not be a shock that network on mobile devices is unreliable. However, the extent of this is sometimes surprising to developers who are new to mobile. That’s why many low level networking strategies are discouraged on mobile devices. Another big surprise for developers is that Apple literally blocks HTTP on their devices unless you have a really good excuse. If you will try to connect to HTTP from an app that doesn’t explicitly enable that the connection will just fail. You need to use HTTPS or ask for a special permission, notice that if you ask for that permission and don’t have a good enough reason your app will be rejected from the appstore. Sockets are usable on mobile devices but they are flaky and hard to use across NATs and devices. We only got server sockets working reliably on Android, they are possible on iOS but they are pretty different there.
 As a solution of sort to some of those issues websockets have risen in recent years and are shaping up to be a very interesting midrange option.
  • 3. Mobile Is Different ✦Network is unreliable ✦iOS Prohibits HTTP and insecure communication ✦Sockets are possible but might be unreliable ✦Server sockets are difficult and less portable ✦WebSockets are rising In this short video I’ll cover some core concepts of networking and webservices on mobile devices and Codename One
 
 First and most importantly for those of you coming from the desktop or server world, this might not be a shock that network on mobile devices is unreliable. However, the extent of this is sometimes surprising to developers who are new to mobile. That’s why many low level networking strategies are discouraged on mobile devices. Another big surprise for developers is that Apple literally blocks HTTP on their devices unless you have a really good excuse. If you will try to connect to HTTP from an app that doesn’t explicitly enable that the connection will just fail. You need to use HTTPS or ask for a special permission, notice that if you ask for that permission and don’t have a good enough reason your app will be rejected from the appstore. Sockets are usable on mobile devices but they are flaky and hard to use across NATs and devices. We only got server sockets working reliably on Android, they are possible on iOS but they are pretty different there.
 As a solution of sort to some of those issues websockets have risen in recent years and are shaping up to be a very interesting midrange option.
  • 4. ConnectionRequest URL Socket WebSocket Builtin Builtin 2 implementations builtin & cn1lib cn1lib Modeled on JavaScript async networking model Modeled on java.net.URL Builtin - async API cn1lib - low level stream API Low level callback API Threaded Seamlessly Manual threading Builtin - seamless threading cn1lib - manual threading Threaded Seamlessly Synchronous & asynchronous API’s Synchronous API Builtin - asynchronous cn1lib - synchronous Asynchronous Highly Portable Portable Builtin - iOS/Android cn1lib - portable but low level Portable Secured thru HTTPS Secured thru HTTPS Insecure Secured thru SSL 4 Network Options The most common networking API in Codename One is Connection request which is paired with the network manager. It’s inspired by JavaScripts asynchronous networking but tries to provide more low level control. The connection request API was developed with a goal of extreme portability and best practices built-in. It’s seamlessly threaded and can automatically work with the EDT as a synchronous or asynchronous API. We also have some support for the URL class which helps port Java SE code to Codename One. It doesn’t use the network manager API and goes directly to the low level API’s. As a result you need to take care of threads yourself and might need to work thru some low level differences in behavior between platforms. We have two socket implementations, one is builtin to Codename One and works asynchronously thru a callback. The other was implemented as a cn1lib and is a lower level API that works directly with the streams. Sockets are inherently very low level and are an advanced API to use. Web sockets serve as a middle of the road approach. They are implemented as a cn1lib as well but use a simplified asynchronous callback API. Since common servers already support websockets, the server side should be a breeze. They are relatively easy to work with and allow sending messages back and forth from the server.
  • 5. Connection Request ConnectionRequest c = new ConnectionRequest(url, false); addToQueue(c); import static com.codename1.ui.CN.*; Before we go to the code notice that in order to use this code you will need to import the CN class statics. Creating a hello world get request is as simple as adding a new connection request to the queue. Notice that the second argument indicates that we are making a GET request and not a POST request which is the default. Also notice that the request is asynchronous so it might not have completed after the addToQueue call. So how do we get the actual data from the URL?
  • 6. 3 Options c.addResponseListener(e -> { byte[] response = e.getConnectionRequest().getResponseData(); // do something with the response data }); ConnectionRequest c = new ConnectionRequest(url, false) { @Override protected void readResponse(InputStream input) throws IOException { // read input stream } }; addToQueueAndWait(c); byte[] response = c.getResponseData(); // do something with the response data There are 3 options… First we can override read response and read the stream directly. This is arguably the best approach as we will only read the data once. Read response is invoked on the network thread so make sure not to change the UI from that method! That is a good thing though as all your processing won’t block the event dispatch thread and won’t slow the app noticeably. The second option uses a response listener to get the result from the connection request. Notice that a response listener occurs on the event dispatch thread so this will slow down execution slightly but you will be able to make changes to the UI directly so the code will be simpler. The same is true about the last and arguably simplest option. When you use addToQueueAndWait instead of addToQueue the current thread is blocked using invokeAndBlock and we can then extract the data. This is pretty convenient for simple requests and we use that often for those cases.
  • 7. Builtin Sockets Socket.connect(server, port, new SocketConnection() { @Override public void connectionError(int errorCode, String message) { Log.p("Error connecting " + errorCode + ": " + message); } @Override public void connectionEstablished(InputStream is, OutputStream os) { while(connected) { // read and write to input/output stream } } }); The builtin sockets use an asynchronous API where the callback method is invoked once connection to the server is established. At that point you will have a thread with two streams and you can just read or write from the streams as you see fit.
  • 8. WebSockets WebSocket sock = new WebSocket(websocketUrl) { @Override protected void onOpen() { // we can start using the websocker } @Override protected void onMessage(String string) { // received string message from server } @Override protected void onMessage(byte[] bytes) { } @Override protected void onError(Exception excptn) { Log.e(excptn); } }; sock.connect() Web sockets are easier, you just receive messages and can send them using the web socket API. Notice that you shouldn’t send any message before onOpen was invoked as you might fail badly… Web sockets are excellent for API’s like chat where a server might trigger a message to a device without the device making a request. This is far more efficient than approaches such as polling which can result in serious battery drain and low performance.
  • 9. URL ✦You can port code that uses java.net.URL to use com.codename1.io.URL ✦You will need to handle threading on your own ✦There is no builtin support for events on the event dispatch thread ✦You might inadvertently rely on low level platform specific behaviors since URL is low level I’ve mentioned URL before and indeed you can use the Codename One URL to port existing code but this also begs the question: why not use URL instead of connection request? Threading is hard would be the first and obvious answer. This is especially true on devices where QA needs to go far and wide Connection request has some builtin capabilities that bind directly to the EDT for instance addToQueueAndWait, progress indicator etc. URL is inherently less portable since it is low level and might expose platform behaviors that you don’t expect a common example is different redirection behavior on 302 for the various OS’s.
  • 10. WebServices ✦WebService wizard can generate server client stubs for remote method call over HTTP ✦ConnectionRequest can be used to invoke typical restful webservices ✦Several cn1lib’s and builtin API’s exist to simplify webservice calls e.g. com.codename1.io.rest.Rest ✦JSONParser & XMLParser support parsing common formats the Result class supports XPath expressions Webservices can be implemented in many ways in Codename One, a common approach is the webservice wizard detailed in the developer guide. It generates method calls that map to server code and allow us to generate a remote function invocation on the server. You can use connection request to invoke rest API’s from the client You can use one of the 3rd party or builtin API’s to connect we have some great API’s such as the REST api that lets you invoke server code with almost no effort You can use the builtin JSON and XML parsers as well as the Result class for xpath expression style parsing. You can also use some of the 3rd party parsers for JSON and XML in the cn1lib section
  • 11. Connection Request WebService ConnectionRequest req = new ConnectionRequest(nextURL, false) { @Override protected void readResponse(InputStream input) throws IOException { JSONParser parser = new JSONParser(); Map response = parser.parseJSON(new InputStreamReader(input, "UTF-8")); items = (List)response.get("items"); nextURL = (String)response.get("nextPage"); } @Override protected void handleException(Exception err) { Log.e(err); } }; addToQueueAndWait(req); Here is a sample rest request from the kitchen sink, you will notice that there isn’t much here, we just parse the data and pass it on based on the response
  • 12. Rest WebService Response<Map> resultData = Rest.get(nextURL). acceptJson().getAsJsonMap(); if(resultData.getResponseCode() != 200) { Log.p("Error code from the server: " + resultData.getResponseCode() + "n"); return; } items = (List)resultData.getResponseData().get("items"); nextURL = (String)resultData.getResponseData().get("nextPage"); We’ve ported that older kitchen sink code to use the new Rest API and this code is even easier. It removes the need for additional classes and can be chained to generate a short expression. We just get a result as a parsed map we can work with, which is very convenient. This API also has an asynchronous version which is similarly convenient
  • 13. Thank You! Thanks for watching, I hope you found this helpful