Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Highlighted
New Developer
Posts: 14
Registered: ‎10-15-2008
My Device: Not Specified
Accepted Solution

Client/Server HTTP or Socket Connections

Hello,

 

I've been trying to create an application that allows me to use either HTTP or a Socket connection to pass information back and fourth from the BES to the BB. Here's essentially what I want to do:

 

  1. Server (BES) sends a request to the Blackberry.
  2. Blackberry recieves the request and sends back some data.

It seems like such a simple process, but I'm having difficulty developing the client/server side applications. So far, I am able to get the BES to send the request to the Blackberry using an HTTP Push from the server (using the Example application from the JDE documentation). However, when I setup an output stream and write the data to it, nothing is seen on the server-side application.

 

Both the Server-side and client-side applications are using listener threads, and both have been implemented mostly in the same way. However, the server-side listener, never receives anything on it's input stream after it sends that initial request.

 

I've scoured the web looking for examples where the Blackberry sends data (not an HTTP request) back to the BES, but just can't find anything.

Below is the selected portion of the code where I think am having difficulty:

 

Client-side App:

 

 

/** * Create a separate listening thread so that you do not * block the application’ main event thread. */ private class ListeningThread extends Thread { private boolean _stop = false; private StreamConnectionNotifier _notify; public synchronized void stop() { _stop = true; try { _notify.close(); // Close the connection so thread returns. } catch (IOException e) { System.err.println(e.toString()); } catch (NullPointerException e) { // The notify object likely failed to open, due to an IOException. } } public void run() { StreamConnection stream = null; InputStream input = null; try { synchronized(this) { // Open the connection once or re-open after an IOException. _notify = (StreamConnectionNotifier)Connector.open(URL); } while (!_stop) { // NOTE: This method blocks until data is received. stream = _notify.acceptAndOpen(); input = stream.openInputStream(); String aString = "ACK"; _infoField.setText("Data: " + aString); OutputStream out = stream.openOutputStream(); String theOutput = "theOUTPUT"; out.write(theOutput.getBytes()); // <-- NEVER REACHES SERVER out.flush(); out.close(); // Write the data to the output stream aString = "Sent"; _infoField.setText("Data: " + aString); } } catch (IOException e) { System.err.println(e.toString()); // It is likely the stream was closed. } } }

 And the server-side App (this portion is just inside a public method):

 

 

try { URL url = getPushURL(HANDHELD_EMAIL); System.out.println("Sending to" + url.toString()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setDoInput(true); //for receiving the confirmation conn.setDoOutput(true); //for sending the data conn.setRequestMethod("POST"); //post the data to the BES OutputStream out = conn.getOutputStream(); out.write(data); //write the data // INPUT STREAM TYPE I InputStreamReader _in = new InputStreamReader(conn.getInputStream()); char[] input = new char[20]; for ( int i = 0; i < 20; ++i ) { input[i] = (char)_in.read(); System.out.println(input[i]); } _in.close(); out.close(); conn.disconnect(); } catch (IOException e) { System.err.println(e); } }

 

 If the entire source code is required I can post that, or if there's any other information needed let me know. I'd really appreciate any help I can get.

 

 

BlackBerry Development Advisor
Posts: 15,784
Registered: ‎07-09-2008
My Device: BlackBerry PRIV
My Carrier: Bell

Re: Client/Server HTTP or Socket Connections

Are you trying to write data back on the connection that arrives to the BlackBerry from the push connection?  If so, this is not supported.  The application should open a new connection back to your server side application.

 

Here are the chain of events that occur:

 

1.  Push application connects to the BlackBerry Enterprise Server and pushes data.  BlackBerry Enterprise Server responds with a response code and the connection is closed.

2.  BlackBerry Enterprise Server attempts to deliver the data to the BlackBerry handheld.  This request can be queued for a period of time if the BlackBerry device is not available (out of coverage, turned off, etc.).

3.  The BlackBerry Enterprise Server connects to the BlackBerry device and delivers the data.

 

As you can see, a push is not an active/direct connection to a BlackBerry device.  Data is handed off to the BlackBerry Enterprise Server and delivered to the BlackBerry.

 

If you just want an acknowledgement that the push was delivered of that it failed, you can make use of a reliable push.  Please have a look at the httppush demo included with the BlackBerry JDE for an example and have a look at this link.

 

What Is - The Push notification format
Article Number: DB-00395

http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800440/What_Is...

Mark Sohm
BlackBerry Development Advisor

Please refrain from posting new questions in solved threads.
Problem solved? Click the Accept As Solution button.
Found a bug? Report it using Issue Tracker
Developer
Posts: 1,415
Registered: ‎07-30-2008
My Device: Not Specified

Re: Client/Server HTTP or Socket Connections

On a related note, you are going to get more flukey failure modes unless you take out all the glib "synchronized for safety"

stuff and figure out what you reall need. For example, while you are in connector.open any calls to stop will block(?!?)

if your synchronized stop method is trying get "this" which run already has.

As a rule, I never synchronize methods and never hold locks while calling other people's code( unless required by

some API's) , especially

when you know you encounter out-of-control entitites like networks or users. Sure, you see examples

that don't work this way but see some  thoughts here for example,

 

http://www.google.com/search?hl=en&q=site%3Asun.com+concurrency+constructs&aq=f&oq=site%3Asun.com+co...

 

New Developer
Posts: 14
Registered: ‎10-15-2008
My Device: Not Specified

Re: Client/Server HTTP or Socket Connections

Thank you so much for the help. That does make sense why it was not working!
New Developer
Posts: 13
Registered: ‎10-25-2008
My Device: Not Specified

Re: Client/Server HTTP or Socket Connections

Hi Mark,

 

            Before posting my query ,I would like to introduce myself.

            I started my career with Symbian C++(Nokia) devices.Developed some apllications like data call,Streaming Audio files(socket communication).

            Then I moved to desktop development VC++,c# for more than a year.

            Now my company wants me to do some R&D for Blackberry devices.

            Can you please suggest me what platform I choose for development.

 

           Should I go for java(which is completely new for me.As i know rich applications can be developed with this on BB.

 

           or

          c# development with VStudio 2008 plugin will also enable me equally for making new applications for  BB.

 

           I know that RIM has not supported C# development officially for BB.But if someone is already a master  of c# then can he/she

go for that on BB....or there is any chance of getting stuck up when developing good aplications involving HTTp communication,

socket comm,FTP, serail Port communication in BB with c# development.

BlackBerry Development Advisor
Posts: 15,784
Registered: ‎07-09-2008
My Device: BlackBerry PRIV
My Carrier: Bell

Re: Client/Server HTTP or Socket Connections

BlackBerry handhelds do not support C# applications, they are Java (J2ME) based devices. 

 

The BlackBerry Plug-in for Microsoft Visual Studio allows you to create an MDS Runtime Application for a BlackBerry device that communicates with a web service.  MDS Runtime Applications use JavaScript.  I recommend you have a look at this getting started page.

 

http://na.blackberry.com/eng/developers/started/

Mark Sohm
BlackBerry Development Advisor

Please refrain from posting new questions in solved threads.
Problem solved? Click the Accept As Solution button.
Found a bug? Report it using Issue Tracker
New Developer
Posts: 23
Registered: ‎10-20-2008
My Device: Not Specified

Re: Client/Server HTTP or Socket Connections

I am attempting a similar task where I am sending data from my Java Server app to the BB device.  That works just fine.  But I also want to allow the user on the BB device sends select data from the device back to my server application on demand.  Is there any example you have or can site that shows how to establish the http connection on the device back to the server side and transfer data from the device back to the server?

Thanks

BlackBerry Development Advisor
Posts: 15,784
Registered: ‎07-09-2008
My Device: BlackBerry PRIV
My Carrier: Bell

Re: Client/Server HTTP or Socket Connections

Yes there is.  Have a look at the httpdemo sample included with the BlackBerry JDE.

Mark Sohm
BlackBerry Development Advisor

Please refrain from posting new questions in solved threads.
Problem solved? Click the Accept As Solution button.
Found a bug? Report it using Issue Tracker
New Developer
Posts: 16
Registered: ‎03-04-2009
My Device: 9000

Re: Client/Server HTTP or Socket Connections

Hi MSohm,

Iam new to BB JDE && Java.

I have to post data to web server and catch the responce.

ex., post username and password to www.***.com.

iam using Direct IP so no worry of proxy.

BB simulator browser is able to connect to web sites.

mine is BB 9000, JDE 4.6.0, jdk1.6.0, jre 1.6, jre6

 

Following is the code i tried but iam getting NullPointerException at openInputstream. plz help me. 

 

        public void run()

        {

            StreamConnection _sc = null;

            HttpConnection _hc = null;

            for(;Smiley Wink

            {

                synchronized(this)

                {                    

                    try

                    {

                        _brunning = true;

                        String szurltobrowse = geturl();

                        szurltobrowse.trim();

                        if(szurltobrowse.length() <= 0)

                            break;

                        Connection _conn = Connector.open(szurltobrowse);

                        if(_conn == null)

                        {

                            _conn = Connector.open(szurltobrowse);

                        }

                        _hc = (HttpConnection)_conn;

                        _hc.setRequestMethod(HttpConnection.POST);

                        _hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                        _hc.setRequestProperty("User-Agent", "BlackBerry/3.2.1");

                        _hc.setRequestProperty("Content-Language", "en-us");

                        _hc.setRequestProperty("Connection", "close");

                        _hc.setRequestProperty("Content-Length", Integer.toString(_szpostdata.length()));

                        

                        OutputStream _os = _hc.openOutputStream();

                        byte[] _datainbytes = _szpostdata.getBytes();

                        _os.write(_datainbytes);

                        //sleep(2000);

                        InputStreamReader _isr = new InputStreamReader( _hc.openInputStream());/*Nullpointerexception*/

                        char[] cdata = new char[256];

                        

                        int istatus = _hc.getResponseCode();

                        if(istatus == HttpConnection.HTTP_OK)

                        {

                            StringBuffer _szdatastream = new StringBuffer();

                            //int ilength = (int)_hc.getLength();

                            int ilength = _isr.read(cdata);

                            if(ilength != -1)

                            {

                                //byte bydata[] = new byte[ilength+1];

                                //ilength = _isr.read(bydata);

                                _szdatastream.append(new String(cdata, 0, ilength));// = new StringBuffer(new String(cdata, 0, ilength));

                            }

                            else

                            {

                                ByteArrayOutputStream _baos = new ByteArrayOutputStream();

                                int ilen = 0;

                                while( (ilen = _isr.read()) != -1)

                                    _baos.write(ilen);

                                _szdatastream.append(new String(_baos.toByteArray()));

                                _baos.close();

                            }

                            /*StringBuffer _szdatabuf = new StringBuffer();

                            //while((ipdata.read(bydata)) > 0)

                            if((ilength = ipdata.read(bydata)) > 0)

                            {

                                _szdatabuf.append(new String(bydata, 0, ilength));

                            }*/

                            String szfinal = _szdatastream.toString();

                            setdata(szfinal);

                            

                            if(szfinal.length() > 0)

                            {

                                _brunning = false;

                                break;

                            }

                        }

                    }

                    catch(Exception e)

                    {

                        _brunning = false;

                        Dialog.alert(e.getMessage());

                    }

                }

            }

        }

 

we can work on any technology.
BlackBerry Development Advisor
Posts: 15,784
Registered: ‎07-09-2008
My Device: BlackBerry PRIV
My Carrier: Bell

Re: Client/Server HTTP or Socket Connections

Open the InputStream after getting the response code to verify that the server returned a 200 OK response.
Mark Sohm
BlackBerry Development Advisor

Please refrain from posting new questions in solved threads.
Problem solved? Click the Accept As Solution button.
Found a bug? Report it using Issue Tracker