TCP Socket Connections BLACKBERRY

Some applications require a lower level of network access than HTTP provides. For example, connecting to a streaming media server, FTP server, or any other non-web server requires a lower level of network access than HTTP provides. In these cases, you can open a TCP socket in much the same way as an HTTP connection by substituting socket:// for http:// - or ssl:// or tls:// for a secure connection.

A Simple Socket Application

We’ll make some simple modifications to the Networking application to perform an HTTP GET using a socket connection instead of the HTTP connection functionality. Because the mechanics are so similar to HTTP connections, and this is a simple (and somewhat contrived) example, we’ll go fairly quickly. Create a new class to perform socket connections. This is analogous to HttpRequestDispatcher but uses SocketConnection instead. We’ll present the code and then discuss it:

package com.beginningblackberry.networking;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
public class SocketConnector extends Thread {
private String host;
private NetworkingMainScreen screen;
public SocketConnector(String host, NetworkingMainScreen screen) {
this.host = host;
this.screen = screen;
}
public void run() {
try {
SocketConnection connection =
(SocketConnection)Connector.open("socket://" + host + ":80");
OutputStream out = connection.openOutputStream();
InputStream in = connection.openInputStream();
String request = "GET / HTTP/1.1\r\n" +
"Host:" + host + "\r\n" +
"\r\n" +
"\r\n";
out.write(request.getBytes());
out.flush();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int firstByte = in.read();
if (firstByte >= 0) {
baos.write((byte)firstByte);
int bytesAvailable = in.available();
while(bytesAvailable > 0) {
byte[] buffer = new byte[bytesAvailable];
in.read(buffer);
baos.write(buffer);
bytesAvailable = in.available();
}
}
baos.close();
connection.close();
screen.requestSucceeded(baos.toByteArray(), "text/plain");
}catch (IOException ex) {
screen.requestFailed(ex.getMessage());
}
}
}

Along with the screen parameter to let us write output, we’re passing in a host.We use this to open the socket connection to port 80, the usual web server port, and to construct the HTTP request because a Host header is required by the HTTP protocol.

NOTE: that you should always specify a port number when opening a socket connection. HTTP connections default to port 80, and HTTPS to port 443, but there’s no concept of a “default” port for a socket connection.

The HTTP request is constructed according to the HTTP protocol specification. we write only the Host header, as it’s the only required one.The first step in reading the response from the socket is this line:

int firstByte = in.read();

This lets us wait for the server to write the first byte of the response back to the socket. Remember, at the socket level, there’s no built-in concept of request-response.The server can theoretically write back at any point or wait any length of time before writing data, so we have to wait and check that the first value we get is not –1, which indicates the server has closed the connection. We then read only as long as bytes are available. In this case, we know the behavior of the server—that it’ll write the entire response as one chunk. In other cases, InputStream.available() tells you only the number of bytes currently available to be read back. More bytes might be available after you’ve finished reading the initial number returned by available.

Adding Socket Support to the Main Screen

To give access to the TCP socket functionality from the main screen, we’ll have the URL field double as a hostname field,so no changes are required to the onscreen controls, just an additional menu item.Add the following lines to makeMenu:

menu.add(new MenuItem("Socket Get", 10, 10) {
public void run() {
socketGet();
}
});

Add the following method to NetworkingMainScreen:

private void socketGet() {
SocketConnector connector = new SocketConnector(urlField.getText(),this);
connector.start();
}

Testing It

Because we’re back to using an MDS connection, remember to enable the MDS in the simulator debug options (or run it from the Start menu). Run the application again and in the URL field, type beginningblackberry.appspot.com. Don’t type a scheme portion for the URL.Then, in the menu, click Socket Get:

Retrieving the web application’s main page using a TCP socket

Retrieving the web application’s main page using a TCP socket

We’re displaying the raw HTTP request, not just the body portion. If you scroll down, you’ll see the same data as we got with the HTTP GET.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

BLACKBERRY Topics