+ All Categories
Home > Documents > Sending and Receiving Data Communications

Sending and Receiving Data Communications

Date post: 22-Feb-2016
Category:
Upload: freya
View: 45 times
Download: 0 times
Share this document with a friend
Description:
Sending and Receiving Data Communications. Dr. Miguel A. Labrador Department of Computer Science & Engineering [email protected] http://www.csee.usf.edu/~labrador. Outline. The Generic Connection Framework The MIDP The Wireless Messaging API Transport Layer Protocols Examples - PowerPoint PPT Presentation
Popular Tags:
26
Sending and Receiving Data Communications Dr. Miguel A. Labrador Department of Computer Science & Engineering [email protected] http://www.csee.usf.edu/~labrador
Transcript
Page 1: Sending and Receiving Data Communications

11

Sending and Receiving DataCommunications

Dr. Miguel A. LabradorDepartment of Computer Science & Engineering

[email protected]://www.csee.usf.edu/~labrador

Page 2: Sending and Receiving Data Communications

2Copyright© Dr. Miguel A. Labrador

2Copyright© Dr. Miguel A. Labrador

2

Outline

• The Generic Connection Framework• The MIDP• The Wireless Messaging API• Transport Layer Protocols• Examples

– TCP, UDP, HTTP, MMS

Page 3: Sending and Receiving Data Communications

3Copyright© Dr. Miguel A. Labrador

3Copyright© Dr. Miguel A. Labrador

3

The Generic Connection Framework (GCF)

• General and extensible classes to support networking capabilities. – Included in the javax.microedition.io package– Includes the Connection interface, which is the foundation object for

all other communication interfaces implemented within the framework

• Connector object acts as a "factory" for creating new connection objects, i.e., instead of using different abstractions for specific forms of communications, a general abstraction is defined that does not define any type of network connection

– Static method open() of javax.microedition.io.Connector class is used to create all connections using a string as an input parameter that describes the target, as follows

Page 4: Sending and Receiving Data Communications

4Copyright© Dr. Miguel A. Labrador

4Copyright© Dr. Miguel A. Labrador

4

GCF

• scheme: communication protocol, e.g., HTTP, TCP, UDP, etc.• target: user, password, host, port and URL of target device• param: param=values

{scheme}:[{target}][{params}]{scheme}://{user}{:password@}{host}{:port}{/url-path}{;parameters}

//HTTP Connection HTTPConnection client = (HTTPConnection)Connector.open("http://www.csee.usf.edu");

//Socket Connection SocketConnection client = (SocketConnection)Connector.open("socket://131.131.2.149:5555");

//Datagram Connection DatagramConnection client = (DatagramConnection)Connector.open("datagram://131.131.2.149:5556");

Page 5: Sending and Receiving Data Communications

5Copyright© Dr. Miguel A. Labrador

5Copyright© Dr. Miguel A. Labrador

5

The Connection APIs• InputConnection and outputConnection

– Unidirectional serial communication– Implement the methods openInputStream, openDataInputStream,

openOutputStream, openOutputDataStream• StreamConnection

– Full duplex serial communication– Combination of the last two

• ContentConnection– Subtype of StreamConnection provides information for HTTP

connections such as content type, encoding, and length• StreamConnectionNotifier

– Waits for clients to request a stream connection– Starts a new StreamConnection to establish the connection

• DatagramConnetion– Input/output of datagrams– Implement methods, send, receive, getMaximumLength

Page 6: Sending and Receiving Data Communications

6Copyright© Dr. Miguel A. Labrador

6Copyright© Dr. Miguel A. Labrador

6

Hierarchy of Connection Interface

Page 7: Sending and Receiving Data Communications

7Copyright© Dr. Miguel A. Labrador

7Copyright© Dr. Miguel A. Labrador

7

The MIDP• Provides second level of communication

– More specific functionalities according to the individual capabilities and resources of the mobile devices

– TCP, UDP, and HTTP• New elements included are:

– SocketConnection: This interface, based on the StreamConnection, implements a full duplex TCP communication between two devices

– SocketServerConnection: This interface, based on the StreamConnectionNotifier, implements the object that waits for TCP connection requests from clients, and creates a StreamConnection when the request is accepted

– UDPDatagramConnection: This interface, based on the DatagramConnection, implements the object that allows a communication using the UDP protocol

– HTTPConnection: This interface, based on the ContentConnection, implements the object that allows HTTP connections

Page 8: Sending and Receiving Data Communications

8Copyright© Dr. Miguel A. Labrador

8Copyright© Dr. Miguel A. Labrador

8

TCP Client ExampleSocketConnection sockConn;

public void tcpSend() { String serverName = "131.131.2.149"; String serverPort = "5555"; //Send data via TCP if(sockConn == null){ try { sockConn = (SocketConnection)

Connector.open("socket://" + serverName + ":" + serverPort); }catch(IOException ex){ System.out.println("Could not create connection: " + ex); }

try { sockConn.setSocketOption(SocketConnection.KEEPALIVE, 1); }catch(IOException ex) { System.out.println("Could not set socket option: " + ex); }

Page 9: Sending and Receiving Data Communications

9Copyright© Dr. Miguel A. Labrador

9Copyright© Dr. Miguel A. Labrador

9

TCP Client Example

try{outstream = sockConn.openOutputStream();

}catch(IOException ex){ System.out.println("Could not open socket stream: " + ex); } } // get the payload byte[] data = getPayload().getBytes(); try { outstream.write(data); }catch(IOException ex){ System.out.println("Could not write to socket stream: " + ex); } }

Page 10: Sending and Receiving Data Communications

10Copyright© Dr. Miguel A. Labrador

10Copyright© Dr. Miguel A. Labrador

10

UDP Client ExampleUDPDatagramConnection dc;

public void udpSend() throws Exception { String serverName = "131.131.2.149"; String serverPort = "5555"; //Send data via UDP if(dc == null){ dc = (UDPDatagramConnection) Connector.open("datagram://" + serverName + ":" + serverPort); } byte[] data = getPayload().getBytes(); Datagram dg = dc.newDatagram(data, data.length); dc.send(dg); dc.close(); //You could leave UDP connection open to avoid overhead of //opening and closing connection repeatedly}

Page 11: Sending and Receiving Data Communications

11Copyright© Dr. Miguel A. Labrador

11Copyright© Dr. Miguel A. Labrador

11

Generic (TCP/UDP) Server Examplepublic class ListenerManager { private static TCPTestServer theTCPServer; private static UDPTestReceiver theUDPReceiver; public static void initialize(){ try{ theTCPServer = new TCPTestServer(31686); theTCPServer.start(); try { theUDPReceiver = new UDPTestReceiver(2009, "lbsbook"); theUDPReceiver.start(); } catch (Exception ex) { Logger.getLogger

(ListenerManager.class.getName()).log(Level.SEVERE, null, ex); } }catch(IOException ioex){ System.err.println("Error initializing a TCPTestServer!"); ioex.printStackTrace(); } } public static void shutdown(){...}}

Page 12: Sending and Receiving Data Communications

12Copyright© Dr. Miguel A. Labrador

12Copyright© Dr. Miguel A. Labrador

12

The TCPTestServer Class

public class TCPTestServer extends Thread {

private final int port; private ServerSocket serv_socket; private LinkedList<ConnectionDump> dump_list;

public TCPTestServer(int port) throws IOException { this.port = port; this.serv_socket = new ServerSocket(port);

// set blocking timeout for accept() call this.serv_socket.setSoTimeout(10*1000); this.dump_list = new LinkedList<ConnectionDump>();}

public void run(){ Socket tmp_socket = new Socket();

Page 13: Sending and Receiving Data Communications

13Copyright© Dr. Miguel A. Labrador

13Copyright© Dr. Miguel A. Labrador

13

The TCPTestServer Class while (this.serv_socket != null){ try{

// this blocks for 10 seconds. tmp_socket = this.serv_socket.accept(); if(tmp_socket.isConnected()){ this.dump_list.add(new ConnectionDump(tmp_socket)); }

}catch(IOException _){} finally{ tmp_socket = null; } }}

public void shutdown(){...}

protected class ConnectionDump extends Thread{...}}

Page 14: Sending and Receiving Data Communications

14Copyright© Dr. Miguel A. Labrador

14Copyright© Dr. Miguel A. Labrador

14

The TCPTestServer Class protected class ConnectionDump extends Thread{

Socket sock; InputStream instream; boolean active; public ConnectionDump(Socket sock){ this.sock = sock; if (sock.isConnected()){ try{ this.instream = sock.getInputStream(); }catch(IOException ioex){ System.err.println("Error getting inputstream for incoming connection."); ioex.printStackTrace(); } } this.active = true; this.start(); }

Page 15: Sending and Receiving Data Communications

15Copyright© Dr. Miguel A. Labrador

15Copyright© Dr. Miguel A. Labrador

15

The TCPTestServer Class public void run(){ while(active){ try{ byte[] b = new byte[124]; this.instream.read(b); // bytes read from the stream System.out.println("TCPTestServer - incoming string:" + new String(b)); }catch(IOException ioex){ System.err.println("Error reading from inputstream"); ioex.printStackTrace(); this.shutdown(); } } } public void shutdown() {...}} }

Page 16: Sending and Receiving Data Communications

16Copyright© Dr. Miguel A. Labrador

16Copyright© Dr. Miguel A. Labrador

16

The UDPTestReceiver Class

public class UDPTestReceiver extends Thread{ DatagramSocket myUDPReceiver; boolean active = true; byte[] recBytes = new byte[150]; DatagramPacket receptorPacket = new DatagramPacket(recBytes,150); private String name; public UDPTestReceiver(int port, String name) throws Exception { myUDPReceiver = new DatagramSocket(port); myUDPReceiver.setSoTimeout(10*1000); this.name = name; }

Page 17: Sending and Receiving Data Communications

17Copyright© Dr. Miguel A. Labrador

17Copyright© Dr. Miguel A. Labrador

17

The UDPTestReceiver Class public void run() { while(active) { try { myUDPReceiver.receive(receptorPacket); String receivedData = new String(receptorPacket.getData()); System.out.println(name+"UDP Received Data->"+receivedData); } catch(SocketTimeoutException e) {

} catch(Exception e) { System.out.println(name+" UDP receiver Exception: "+e); } } myUDPReceiver.close(); myUDPReceiver = null; } public boolean isActive(){...}

public void setActive(boolean active){...}}

Page 18: Sending and Receiving Data Communications

18Copyright© Dr. Miguel A. Labrador

18Copyright© Dr. Miguel A. Labrador

18

HTTP Request Example

public class BasicBrowser extends MIDlet implements CommandListener {

private boolean midletPaused = false; private Command exitCommand; private Command okCommand; private Form form; private StringItem stringItem; private TextField textField; /** * The HelloMIDlet constructor. */ public HelloMIDlet() { }

Page 19: Sending and Receiving Data Communications

19Copyright© Dr. Miguel A. Labrador

19Copyright© Dr. Miguel A. Labrador

19

HTTP Request Examplepublic void commandAction(Command command, Displayable displayable) { if (displayable == form) { if (command == exitCommand) { exitMIDlet(); } else if (command == okCommand) { try { Thread t = new Thread(){

public void run(){ try{ getSimplePage(textField.getString()); }catch(IOException ex){ ex.printStackTrace(); }

} }; t.start(); } catch(Exception e) { e.printStackTrace(); } } }}

Page 20: Sending and Receiving Data Communications

20Copyright© Dr. Miguel A. Labrador

20Copyright© Dr. Miguel A. Labrador

20

HTTP Request Exampleprivate void getSimplePage(String url) throws IOException { StringBuffer buffer = new StringBuffer(); InputStream the_input_stream; HttpConnection the_connection; try { int i = 0; long tam = 0 ; int a_byte = 0; the_connection = (HttpConnection)Connector.open(url); the_input_stream = the_connection.openInputStream(); tam =the_connection.getLength(); if( tam != -1) { for(i = 0 ; i < tam ; i++ ) if((a_byte = the_input_stream.read()) != -1) { buffer.append((char) a_byte); } stringItem.setText("\n The code of the webpage is:\n" + buffer.toString()); } else { stringItem.setText("\n Sorry but the entered URL is not supported."); } } finally { the_input_stream.close(); the_connection.close(); }}

Page 21: Sending and Receiving Data Communications

21Copyright© Dr. Miguel A. Labrador

21Copyright© Dr. Miguel A. Labrador

21

The Wireless Messaging API (WMA)• Messaging capability to mobile devices using the cellular network• Short Messaging Service (SMS)

– Exchanges text-only messages• Multimedia Messaging Service (MMS),

– Extends the capabilities of the SMS messages by allowing embedded multimedia content in the message

• WMA main components:– MessageConnection: Interface based on the basic Connection

interface that creates the connection between two devices and allows the transmission of a message

– Message: This interface is designed to model a basic message object. The WMA defines three different types of messages:

• BynaryMessage: A message with a binary array of data• TextMessage: A text message• MultipartMessage: A message that can carry also multimedia content, or

a MMS message

Page 22: Sending and Receiving Data Communications

22Copyright© Dr. Miguel A. Labrador

22Copyright© Dr. Miguel A. Labrador

22

The Wireless Messaging API (WMA)• WMA main components:

– MessagePart: Models the individual sections of a MultipartMessage object

• This object contains the definition of the message content according to the MIME standard and the data related to the content, either binary or text

– MessageListener: Defines a mechanism to notify that a new message has arrived

• Acknowledges the independence between the notification of the arrival of a message and the actual reception of the message that includes bringing the information to the device in order to avoid blocking the MessageListener from other notifications

• Addressing in the messaging domain is different– Destination address in a SMS messages is identified by the phone

number registered in the SIM card of the phone– In the case of MMS messages, the destination address can assume

multiple formats: an email address, phone number, IPv4 or IPv6 IP addresses

Page 23: Sending and Receiving Data Communications

23Copyright© Dr. Miguel A. Labrador

23Copyright© Dr. Miguel A. Labrador

23

Addressing in WMA• In both, SMS and MMS messages a parameter is important to

define the communication port that will receive the message– SMS uses numeric port– MMS uses a 32 character long string

– getAppProperty() method obtains values from parameters of the application defined in the JAD file

String appID = getAppProperty("MmsAppID");String address = "mms://+555123456:" + appID;int sms_port = getAppProperty("SmsAppCommPort");

//SMS message(MessageConnection)Connector.open ("sms://+555123456"+sms_port);

//MMS message(MessageConnection)Connector.open (address);

SmsAppCommPort: 51234MmsAppID: wma_example_app

Page 24: Sending and Receiving Data Communications

24Copyright© Dr. Miguel A. Labrador

24Copyright© Dr. Miguel A. Labrador

24

The WMA Hierarchy

Page 25: Sending and Receiving Data Communications

25Copyright© Dr. Miguel A. Labrador

25Copyright© Dr. Miguel A. Labrador

25

MMS Examplefinal public void sendMessage(

Thread th = new Thread() {public void run(){

MessageConnection connection=null; String appID = getAppProperty("MmsAppID"); try { String address="mms://[email protected]"; //Establishing connection connection=(MessageConnection)Connector.open("mms://:"+appID); //Create a multipart message MultipartMessage message=(MultipartMessage)

connection.newMessage(MessageConnection.MULTIPART_MESSAGE, address);

message.setSubject("LOCATIONUPDATE"); MessagePart locationPart=new MessagePart(getLocationInfo().getBytes(), "text/html", "id:2", "text", null); message.addMessagePart(locationPart); connection.send(message); }catch(Exception e){ //Handle exception}

Page 26: Sending and Receiving Data Communications

26Copyright© Dr. Miguel A. Labrador

26Copyright© Dr. Miguel A. Labrador

26

MMS Example

if(connection!=null) { try { connection.close(); }catch(Exception e){//Handle exception} } }

};th.start();

}


Recommended