Cosc 4755

Download Cosc  4755

Post on 29-Jan-2016

21 views

Category:

Documents

0 download

Embed Size (px)

DESCRIPTION

Cosc 4755. Mobile networking Overview and Stream, Socket, and Datagram. A Overview. Generic Connection Framework (GCF) In Javax.microedition.io Now includes files, more network protocols, smart cards, RFID cards, bluetooth , and bar codes. And is being ported back to Java SE as JSR 197. - PowerPoint PPT Presentation

TRANSCRIPT

Cosc 4755

Cosc 4755Mobile networkingOverview and Stream, Socket, and Datagram.A Overview

Generic Connection Framework (GCF)In Javax.microedition.ioNow includes files, more network protocols, smart cards, RFID cards, bluetooth, and bar codes.And is being ported back to Java SE as JSR 197Some Connection SchemesURL SchemeProtocolGCF TypeDefined byRequiredBtl2capBluetoothL2CAPConnectionJSR 82NodatagramDatagramDatagramConnectionCLDC, CDC, JSR 197NofileFile accessFileConnection, InputConnectionJSR 75NohttpHTTPHttpConnectionMIDP 1.0/2.0YeshttpsSecure HTTPHttpsConnectionMIDP 2.0yescomSerial I/OCommConnectionMIDP 2.0nosms, mmsSMS, MMSMessageConnectionJSR 120, JSR 205NoapduApplication Protocol Data Unit (encryption and smart cards)APDUConnectionJSR 177nosocket, serversocketSocketSocketConnection, ServerSocketConnectionMIDP 2.0nodatagramUDPUDPDatagramConnectionMIDP 2.0noImplemented under profilesConnectionRequired?CLCD 1.0, 1.1MIDP 1.0MIDP 2.0CommConnectionNYesConnectionYYesYesYesContentConnectionYYesYesYesDatagramConnectionNyesyesyesHttpConnectionYyesyesyesHttpsConnectionYyesyesyesInputConnectionYyesyesyesOutputConnectionYyesyesyesSecureConnectionNYesServerSocketConnectionNYesSocketConnectionNYesStreamConnectionYyesyesyesStreamConnectionNotifierYyesyesyesUDPDatagramConnectionNYesNormally implemented, but carrier or handset may not.Common Connections Connector class is the abstracted viewLike when we used for file access.Connection interface, generic connectiondefines the close methodDatagramConnection interface, defines actions for a datagram connection, like UDPDatagram interface, abstract interface for a datagram, which are bidirectional, extending the DataInput and DataOutput interfacesStreamConnection, defines actions on a stream connection, such as TCPbidirectional, uses the InputConnection and OutputConnectionContentConnection interface, supports passes content encoded through a well-known codecVideo, audio, images.Permission for Network ConnectionNetwork applications require privilege, which is imposed by the MIDLet.This ensures that unauthorized network connection do not result in data use charges.On a phone, may require sign appAt min, requires the JAD to specify the privileges they require, set in the JAD attributes MIDlet-PermissionsSee Pg 327 in the book for more info.In the emulators, you app's runs as untrusted and connections are available if the user grants permissionURL syntaxscheme://user:password@host:port/path;parametersWherescheme is the protocol (ie http, file, etc)user is the username, which is optionalpassword is the password for the username, also optionalhost is the fully qualified domain name or addressport is the optional port number, scheme provides the defaultpath is the path on the remote endthe format varies by scheme.Parameters are optional parameters, depends on scheme.typical network code.String url = "socket://www.nowhere.com:3012";StreamConnection c = null;InputStream s = null; try { c = (StreamConnection)Connector.open(url); s = c.openInputStream(); int ch; while ((ch = s.read()) != -1) { //read every character until end of file (-1). } } catch (ConnectionNotFoundException e) { } catch (IllegalArgumentException e) { } catch (IOException e) { } finally { if (s != null) s.close(); if (c != null) c.close(); } StreamConnectionIs the general method to open a network connection.only provides openDataInputStream, openInputStream, openDataOutputStream, openOutputStream, and close methods.The following inherit StreamConnectionCommConnection, ContentConnection, HttpConnection, HttpsConnection, SecureConnection, SocketConnectionSocketConnectionSocketConnection, provides us with the TCP connection (as does StreamConnection)Provides methods some methods like we use in java SE and general UNIX socket programming.String getAddress()Gets the remote address to which the socket is bound. String getLocalAddress()Gets the local address to which the socket is bound. int getLocalPort()Returns the local port to which this socket is bound. int getPort()Returns the remote port to which this socket is bound. int getSocketOption(byteoption)Get a socket option for the connection. void setSocketOption(byteoption, intvalue)Set a socket option for the connection.SocketConnection (2)Byte OptionDELAY: Socket option for the small buffer writing delay.KEEPALIVE: Socket option for the keep alive feature. LINGER: Socket option for the linger time to wait in seconds before closing a connection with pending data output. RCVBUF:Socket option for the size of the receiving buffer. SNDBUF: Socket option for the size of the sending buffer.Examples.setSocketOption(SocketConnection.DELAY,0);basically like flush(), send small packets.int x = s.getSocketOption(SocketConnection.RCVBUF);how big is the receive buffer?Socket Exampleimport javax.microedition.io.*;import java.io.*;

String url = "socket://Somewhere.com:3012"; try { //connection should be it own method too.sock = (SocketConnection)Connector.open(url); in = new InputStreamReader(sock.openInputStream()); out = new OutputStreamWriter(sock.openOutputStream()); writeLine("Hi from a phone."); System.out.println("Wrote to System");System.out.println("Now Waiting on input"); String from = getLine(); System.out.println("Server said:"+from); } catch (ConnectionNotFoundException e) { System.out.println("Something happened, ConnectionNotFoundException"); } catch (IllegalArgumentException e) { System.out.println("Something happened, IllegalArgumentException"); } catch (IOException e) { System.out.println("Something happened, IOExecption"); } finally { try { //close should be it's own method too. if (sock != null) sock.close(); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ex) { sock=null; in =null; out=null; } }And getLine and writeLine methods: public void writeLine(String to) { to +="\n"; if (out != null) { try { out.write(to.toCharArray(), 0, to.length()); } catch (IOException e) { label.setText("Failed to write"); } } } public String getLine() { // read from network port and have default value String from = ""; char ch; int i; if (in != null) { try { i = in.read(); while (i != -1 && (char) i != '\n') { from += (char) i; i = in.read(); } } catch (IOException e) { from = "AWGH!!!"; } } return (from); }Datagram and DatagramConnectionDatagram and DatagramConnection are for UDP networking.These work differently then Stream and Socket connection.A datagramConnection, sends/receives a datagram.There is no methods for OpenInputData and openOutputData streams.A datagramConnection can be a client or serverDatagramConnectionlike everything else, uses connector.DatagramConnection dgc = null;Client url = "data://somwhere.com:3012";dgc = (DatagramConnection)Connector.open(url);Serverurl = "data://:3012"; //note no hostname!dgc = (DatagramConnection)Connector.open(url);

datagramUDP is a connectionless protocolA datagram is the packet, which is sent or received.Datagram hasbuffer, which is the dataoffset, which is the pointer to current read or writelength, which is the size of the buffer.header information is also availableThere is also a reset method, to reuse the datagram.datagram (2)The datagram uses the DataInput/Output methodsreadBoolean, writeBooleanreadByte, WriteBytereadChar, writeCharreadFloat, writeFloatreadShort, writeShorereadInt, writeIntreadLong, writeLongreadUTF, writeUTFreadFully, writeread/write an array of bytes.datagram (3)Again, we can work with Strings instead.Using the String functions to read/write bytes.

datagram has the two following methods (and the constructor)byte[] = getData() //return the data buffersetData(byte[] b, int offset, int length) //set bufferUDP exampleimport javax.microedition.io.*;import java.io.*;

String url = "datagrame://somewhere.com:3012"; DatagramConnection dgc = null; Datagram d; String s = "Hello World"; byte m[] = s.getBytes(); String t; try { dgc = (DatagramConnection) Connector.open(url); //create the datagram with the data d = dgc.newDatagram(m,m.length); //send the datagram dgc.send(d); //now receive a datagram d.reset(); //reset for reuse dgc.receive(d); t = new String(d.getData()); System.out.println("Recieved: "+t); } catch (IOException ex) { }

Server side.Sounds like an odd idea for a phone, but there are a number of reasonMainly, what is called, "push" data sent to the phone. email and other informationUDP uses the same as before, no host name and use receive method.TCP, uses ServerSocketConnection method.

ServerSocketConnectionSimilar to a UNIX methods (java's too)Like UDP, no host is url line.url = "socket://:3012";There is an acceptAndOpen() methodreturns a SocketConnectionuseful methodsString getLocalAddress()int getLocalPort()ServerSocketConnection Exampleimport javax.microedition.io.*;import java.io.*;private InputStreamReader in = null;private OutputStreamWriter out = null;private SocketConnection sock = null;private ServerSocketConnection ssc = null;String url="socket://:3012"; try { ssc = (ServerSocketConnection) Connector.open(url); System.out.println("localaddress is "+ssc.getLocalAddress()); sock = (SocketConnection)ssc.acceptAndOpen(); in = new InputStreamReader(sock.openInputStream()); out = new OutputStreamWriter(sock.openOutputStream()); //just like SocketConnection now //and close the sock, in, and out ssc.close(); } catc