260 likes | 417 Views
Sending and Receiving Data Communications. Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador. Outline. The Generic Connection Framework The MIDP The Wireless Messaging API Transport Layer Protocols Examples
E N D
Sending and Receiving DataCommunications Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador
Outline • The Generic Connection Framework • The MIDP • The Wireless Messaging API • Transport Layer Protocols • Examples • TCP, UDP, HTTP, MMS
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
GCF {scheme}:[{target}][{params}] {scheme}://{user}{:password@}{host}{:port}{/url-path}{;parameters} • scheme: communication protocol, e.g., HTTP, TCP, UDP, etc. • target: user, password, host, port and URL of target device • param: param=values //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");
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
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
TCP Client Example SocketConnectionsockConn; 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); }
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); } }
UDP Client Example UDPDatagramConnection 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 }
Generic (TCP/UDP) Server Example public class ListenerManager { private static TCPTestServertheTCPServer; private static UDPTestReceivertheUDPReceiver; 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(IOExceptionioex){ System.err.println("Error initializing a TCPTestServer!"); ioex.printStackTrace(); } } public static void shutdown(){...} }
The TCPTestServer Class public class TCPTestServer extends Thread { private final int port; private ServerSocketserv_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();
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{...} }
The TCPTestServer Class protected class ConnectionDump extends Thread{ Socket sock; InputStreaminstream; boolean active; public ConnectionDump(Socket sock){ this.sock = sock; if (sock.isConnected()){ try{ this.instream = sock.getInputStream(); }catch(IOExceptionioex){ System.err.println("Error getting inputstream for incoming connection."); ioex.printStackTrace(); } } this.active = true; this.start(); }
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(IOExceptionioex){ System.err.println("Error reading from inputstream"); ioex.printStackTrace(); this.shutdown(); } } } public void shutdown() {...} } }
The UDPTestReceiver Class public class UDPTestReceiver extends Thread { DatagramSocketmyUDPReceiver; boolean active = true; byte[] recBytes = new byte[150]; DatagramPacketreceptorPacket = 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; }
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 booleanisActive(){...} public void setActive(boolean active){...} }
HTTP Request Example public class BasicBrowser extends MIDlet implements CommandListener { private booleanmidletPaused = false; private Command exitCommand; private Command okCommand; private Form form; private StringItemstringItem; private TextFieldtextField; /** * The HelloMIDlet constructor. */ public HelloMIDlet() { }
HTTP Request Example public 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(); } } } }
HTTP Request Example private void getSimplePage(String url) throws IOException { StringBuffer buffer = new StringBuffer(); InputStreamthe_input_stream; HttpConnectionthe_connection; try { inti = 0; long tam = 0 ; inta_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(); } }
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
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
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; intsms_port = getAppProperty("SmsAppCommPort"); //SMS message (MessageConnection)Connector.open ("sms://+555123456"+sms_port); //MMS message (MessageConnection)Connector.open (address); SmsAppCommPort: 51234 MmsAppID: wma_example_app
MMS Example final public void sendMessage( Thread th = new Thread() { public void run(){ MessageConnection connection=null; String appID = getAppProperty("MmsAppID"); try { String address="mms://lbsbook@mail.usf.edu"; //Establishing connection connection=(MessageConnection)Connector.open("mms://:"+appID); //Create a multipart message MultipartMessage message=(MultipartMessage) connection.newMessage(MessageConnection.MULTIPART_MESSAGE, address); message.setSubject("LOCATIONUPDATE"); MessagePartlocationPart=new MessagePart(getLocationInfo().getBytes(), "text/html", "id:2", "text", null); message.addMessagePart(locationPart); connection.send(message); }catch(Exception e){ //Handle exception}
MMS Example if(connection!=null) { try { connection.close(); }catch(Exception e){//Handle exception} } } }; th.start(); }