580 likes | 835 Views
제 9 장 MIDP Network Programing. J2SE 와 J2ME Network Programing Generric Connection Framework Socket 을 이용한 무선네트워크 프로그래밍 Http connection 을 이용한 무선네트워크 example. J2SE 와 J2ME Network Programing 차이. Library 의 차이 기기의 성능의 차이 3. 무선 통신의 방법
E N D
제9장 MIDP Network Programing J2SE와 J2ME Network Programing Generric Connection Framework Socket을 이용한 무선네트워크 프로그래밍 Http connection을 이용한 무선네트워크 example
J2SE와 J2ME Network Programing 차이 • Library의 차이 • 기기의 성능의 차이 3. 무선 통신의 방법 가. packet-switched 방식: 전송할 정보를 packet단위로 나누어 스트림을 통해 전송한 후, 반대편에서 재 조합하여 통신을 연결. : 장점- 효율성, 단점: 안정성 보장 못함. 나. Circuit-switched 방식: end-to-end 회로를 통한 전화통신용 연결을 만들고 통신을 한다. 통신을 하는 동안 회로는 열려있고, 네트워크자원의 고정된 자원을 사용함으로써 사용자의 독점적인 사용권을 보장한다. 장점은 통신의 안정성을 보장하고, 단점은 자원의 효율성이 떨어진다는 점이다.
2.무선통신의 특징 • Device들의 다양성 : 특정기기에 맞는 library를 제공할 수가 없다. • 해결 방법 : CLDC에서 Generic Connection Framework을 지원하여 이를 기반으로 각 벤더들이 자사의 Device에 맞게 구현하도록 함. • GCF : CLDC 기반의 profile 들을 각 기기들에 맞는 새로운 API로 정의하여 이를 각 벤더들의 제품에 맞게 구현하도록 library를 공개 함. (MIDP, PDAP 등) • 광범위한 기기들에게 호환이 될 수있게 네트워크 와 I/O를 추상화 하여 Interface로 제공함.
3. Generic Connection Framework의 설계목표 • 서로 다른 형태의 입출력 형태를 일관성 있게 지원한다. • 서로 다른 형태의 프로토콜을 일관성 있게 지원한다. • 애플리케이션의 프로토콜을 일관성 있게 지원한다. • 표준 자바 클래스 라이브러리와의 상위 호환성을 가진다.
3-1. Generic Connection Framework 계층도 게층도 Connection StreamConnectionNotifier DatagramConnection InputConnection OutputConnection StreamConnection ContentConnection HttpConnection
3-2. Connection Framework 패키지 • Connection :Generic Connection Framework에서 가장 기본이 되는 최상위 인터페이스 • InputConnection :데이터를 읽어 들일 수 있는 디바이스를 표현하는 연결형 • OutputConnection :데이터를 전송할 수 있는 디바이스를 표현하는 연결형 • StreamConnection :단순히 InputConnection과 OutputConnection을 통합하기 위한 인터페이스. 커뮤니케이션 인터페이스를 실제로 구현하는 클래스를 위한 논리적인 출발점을 제공
3-3. Connection Framework 패키지 • ContentConnection :HTTP 연결에 의한 기본적인 메타데이터 정보에 대한 접근을 제공하는 StreamConnection의 하위 인터페이스 • HttpConnection :HTTP 연결에 필요한 메소드와 상수를 정의 • StreamConnectionNotifier :연결이 설정될 때까지 기다리기 위해 사용되는 연결형. acceptAndOpen() 메소드는 클라이언트 프로그램이 연결될 때까지 블록되고, 연결이 설정되면 StreamConnection을 리턴 • DatagramConnection :데이터그램 종단을 표현하기 위한 연결형
Interface Summary 3-4. Interface Summary Connection This is the most basic type of generic connection. ContentConnection This interface defines the stream connection over which content is passed. Datagram This is the generic datagram interface. DatagramConnection This interface defines the capabilities that a datagram connection must have. HttpConnection This interface defines the necessary methods and constants for an HTTP connection. InputConnection This interface defines the capabilities that an input stream connection must have. OutputConnection This interface defines the capabilities that an output stream connection must have. StreamConnection This interface defines the capabilities that a stream connection must have. StreamConnectionNotifier This interface defines the capabilities that a connection notifier must have.
Class Summary 3-5. Class Summary Connector This class is a placeholder for the static methods that are used for creating all the Connection objects. Exception Summary ConnectionNotFoundException This class is used to signal that a connection target cannot be found.
3-6. javax.microedition.io Class Connector • Field Summary • staticintREADAccess mode READ. • staticintREAD_WRITEAccess mode READ_WRITE. • staticintWRITEAccess mode WRITE.
Method Summary 3-7. 메소드 staticConnection open(Stringname)Create and open a Connection. staticConnection open(Stringname, intmode)Create and open a Connection. staticConnection open(Stringname, intmode, booleantimeouts)Create and open a Connection. staticDataInputStream openDataInputStream(Stringname)Create and open a connection input stream. staticDataOutputStream openDataOutputStream(Stringname)Create and open a connection output stream. staticInputStream openInputStream(Stringname)Create and open a connection input stream. staticOutputStream openOutputStream(Stringname)Create and open a connection output stream.
3-8. ConnectionNotFoundException • public class ConnectionNotFoundException extends IOException • Constructor Summary ConnectionNotFoundException()Constructs a ConnectionNotFoundException with no detail message. ConnectionNotFoundException(Strings)Constructs a ConnectionNotFoundException with the specified detail message.
4-1. Interface Connection Method Summary void close()Close the connection. • javax.microedition.io Interface Connection • All Known Subinterfaces: • ContentConnection, DatagramConnection, HttpConnection, InputConnection, OutputConnection, StreamConnection, StreamConnectionNotifier public interface Connection This is the most basic type of generic connection. Only the close method is defined. The open method is not defined here because opening is always done using the Connector.open() methods.
4-2. Interface ContentConnection Method Summary String getEncoding()Returns a string describing the encoding of the content which the resource connected to is providing. long getLength()Returns the length of the content which is being provided. String getType()Returns the type of content that the resource connected to is providing. • javax.microedition.io Interface ContentConnection • All Superinterfaces: • Connection, InputConnection, OutputConnection, StreamConnection • All Known Subinterfaces: • HttpConnection public interface ContentConnection extends StreamConnection This interface defines the stream connection over which content is passed.
4-3. Interface Datagram • javax.microedition.io Interface Datagram • All Superinterfaces: • DataInput, DataOutput • public interface Datagram extends DataInput, DataOutput
4-3-1. Method Summary • StringgetAddress()Get the address in the datagram. • byte[]getData()Get the buffer. • intgetLength()Get the length. • intgetOffset()Get the offset. • voidreset()Zero the read/write pointer as well as the offset and length parameters. • voidsetAddress(Datagramreference)Set datagram address, copying the address from another datagram. • voidsetAddress(Stringaddr)Set datagram address. • voidsetData(byte[]buffer, intoffset, intlen)Set the buffer, offset and length. • voidsetLength(intlen)Set the length.
4-4. Interface DatagramConnection • javax.microedition.io Interface DatagramConnection • All Superinterfaces: • Connection • public interface DatagramConnection • extends Connection
Method Summary 4-4-1. Method Summary int getMaximumLength()Get the maximum length a datagram can be. int getNominalLength()Get the nominal length of a datagram. Datagram newDatagram(byte[]buf, intsize)Make a new datagram object. Datagram newDatagram(byte[]buf, intsize, Stringaddr)Make a new datagram object. Datagram newDatagram(intsize)Make a new datagram object automatically allocating a buffer. Datagram newDatagram(intsize, Stringaddr)Make a new datagram object. void receive(Datagramdgram)Receive a datagram. void send(Datagramdgram)Send a datagram.
4-5. Interface HttpConnection • javax.microedition.io Interface HttpConnection • All Superinterfaces: • Connection, ContentConnection, InputConnection, OutputConnection, StreamConnection • public interface HttpConnection • extends ContentConnection
getRequestMethod() setRequestMethod() getRequestProperty() setRequestProperty() () getResponseCode() getResponseMessage() getHeaderFieldInt getHeaderFieldDate getExpiration getDate getLastModified getHeaderField getHeaderFieldKey 4-5-1. 메소드 • getLength() • getType() • getEncoding() • getHeaderField
4-6. Interface InputConnection Method Summary DataInputStream openDataInputStream()Open and return a data input stream for a connection. InputStream openInputStream()Open and return an input stream for a connection. • javax.microedition.io Interface InputConnection • All Superinterfaces: • Connection • All Known Subinterfaces: • ContentConnection, HttpConnection, StreamConnection public interfaceInputConnection extends Connection This interface defines the capabilities that an input stream connection must have.
4-7. Interface OutputConnection Method Summary DataOutputStream openDataOutputStream()Open and return a data output stream for a connection. OutputStream openOutputStream()Open and return an output stream for a connection. • javax.microedition.io Interface OutputConnection • All Superinterfaces: • Connection • All Known Subinterfaces: • ContentConnection, HttpConnection, StreamConnection public interface OutputConnection extends Connection This interface defines the capabilities that an output stream connection must have.
4-8. Interface StreamConnection Methods inherited from interface javax.microedition.io.InputConnection openDataInputStream, openInputStream Methods inherited from interface javax.microedition.io.Connection close Methods inherited from interface javax.microedition.io.OutputConnection openDataOutputStream, openOutputStream • javax.microedition.ioInterface StreamConnection • All Superinterfaces: • Connection, InputConnection, OutputConnection • All Known Subinterfaces: • ContentConnection, HttpConnection public interface StreamConnection extends InputConnection, OutputConnection This interface defines the capabilities that a stream connection must have.
4-9. Interface StreamConnectionNotifier Method Summary StreamConnection acceptAndOpen()Returns a StreamConnection that represents a server side socket connection. Methods inherited from interface javax.microedition.io.Connection close • All Superinterfaces: • Connection public interface StreamConnectionNotifier extends Connection This interface defines the capabilities that a connection notifier must have.
4-10. Interface HttpConnection • javax.microedition.io Interface HttpConnection • All Superinterfaces: • Connection, ContentConnection, InputConnection, OutputConnection, StreamConnection • public interface HttpConnection • extends ContentConnection
Field Summary 4-10-1. Field Summary1 staticString GETHTTP Get method. staticString HEADHTTP Head method. staticint HTTP_ACCEPTED202: The request has been accepted for processing, but the processing has not been completed. staticint HTTP_BAD_GATEWAY502: The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request. staticint HTTP_BAD_METHOD405: The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. staticint HTTP_BAD_REQUEST400: The request could not be understood by the server due to malformed syntax. staticint HTTP_CLIENT_TIMEOUT408: The client did not produce a request within the time that the server was prepared to wait. staticint HTTP_CONFLICT409: The request could not be completed due to a conflict with the current state of the resource. staticint HTTP_CREATED201: The request has been fulfilled and resulted in a new resource being created. staticint HTTP_ENTITY_TOO_LARGE413: The server is refusing to process a request because the request entity is larger than the server is willing or able to process. staticint HTTP_EXPECT_FAILED417: The expectation given in an Expect request-header field could not be met by this server, or, if the server is a proxy, the server has unambiguous evidence that the request could not be met by the next-hop server. staticint HTTP_FORBIDDEN403: The server understood the request, but is refusing to fulfill it. staticint HTTP_GATEWAY_TIMEOUT504: The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI or some other auxiliary server it needed to access in attempting to complete the request.
staticint 4-10-2. Field Summary2 HTTP_GONE410: The requested resource is no longer available at the server and no forwarding address is known. staticint HTTP_INTERNAL_ERROR500: The server encountered an unexpected condition which prevented it from fulfilling the request. staticint HTTP_LENGTH_REQUIRED411: The server refuses to accept the request without a defined Content- Length. staticint HTTP_MOVED_PERM301: The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. staticint HTTP_MOVED_TEMP302: The requested resource resides temporarily under a different URI. staticint HTTP_MULT_CHOICE300: The requested resource corresponds to any one of a set of representations, each with its own specific location, and agent- driven negotiation information is being provided so that the user (or user agent) can select a preferred representation and redirect its request to that location. staticint HTTP_NO_CONTENT204: The server has fulfilled the request but does not need to return an entity-body, and might want to return updated meta-information. staticint HTTP_NOT_ACCEPTABLE406: The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request. staticint HTTP_NOT_AUTHORITATIVE203: The returned meta-information in the entity-header is not the definitive set as available from the origin server. staticint HTTP_NOT_FOUND404: The server has not found anything matching the Request-URI. staticint HTTP_NOT_IMPLEMENTED501: The server does not support the functionality required to fulfill the request. staticint HTTP_NOT_MODIFIED304: If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. staticint HTTP_OK200: The request has succeeded.
staticint 4-10-3. Field Summary3 HTTP_PARTIAL206: The server has fulfilled the partial GET request for the resource. staticint HTTP_PAYMENT_REQUIRED402: This code is reserved for future use. staticint HTTP_PRECON_FAILED412: The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. staticint HTTP_PROXY_AUTH407: This code is similar to 401 (Unauthorized), but indicates that the client must first authenticate itself with the proxy. staticint HTTP_REQ_TOO_LONG414: The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret. staticint HTTP_RESET205: The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent. staticint HTTP_SEE_OTHER303: The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource.
staticint 4-10-4. Field Summary4 HTTP_TEMP_REDIRECT307: The requested resource resides temporarily under a different URI. staticint HTTP_UNAUTHORIZED401: The request requires user authentication. staticint HTTP_UNAVAILABLE503: The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. staticint HTTP_UNSUPPORTED_RANGE416: A server SHOULD return a response with this status code if a request included a Range request-header field , and none of the range-specifier values in this field overlap the current extent of the selected resource, and the request did not include an If-Range request-header field. staticint HTTP_UNSUPPORTED_TYPE415: The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. staticint HTTP_USE_PROXY305: The requested resource MUST be accessed through the proxy given by the Location field. staticint HTTP_VERSION505: The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. staticString POSTHTTP Post method.
Method Summary 4-10-5. Method Summary1 long getDate()Returns the value of the date header field. long getExpiration()Returns the value of the expires header field. String getFile()Returns the file portion of the URL of this HttpConnection. String getHeaderField(intn)Gets a header field value by index. String getHeaderField(Stringname)Returns the value of the named header field. long getHeaderFieldDate(Stringname, longdef)Returns the value of the named field parsed as date. int getHeaderFieldInt(Stringname, intdef)Returns the value of the named field parsed as a number. String getHeaderFieldKey(intn)Gets a header field key by index. String getHost()Returns the host information of the URL of this HttpConnection. long getLastModified()Returns the value of the last-modified header field. int getPort()Returns the network port number of the URL for this HttpConnection. String getProtocol()Returns the protocol name of the URL of this HttpConnection.
String 4-10-6. Method Summary2 getQuery()Returns the query portion of the URL of this HttpConnection. String getRef()Returns the ref portion of the URL of this HttpConnection. String getRequestMethod()Get the current request method. String getRequestProperty(Stringkey)Returns the value of the named general request property for this connection. int getResponseCode()Returns the HTTP response status code. String getResponseMessage()Gets the HTTP response message, if any, returned along with the response code from a server. String getURL()Return a string representation of the URL for this connection. void setRequestMethod(Stringmethod)Set the method for the URL request, one of: GET POST HEAD are legal, subject to protocol restrictions. void setRequestProperty(Stringkey, Stringvalue)Sets the general request property. Methods inherited from interface javax.microediti
5. Connector 클래스 • 네트워크 커넥션 만들기 InputConnection ic = (InputConnection)Connector.open(“http://www.webyu.com”, Connector.READ, false); • DataInputStream dis = ic.openDataInputStream();
5-1. Connection 생성방법1 • Connector.open(“protocol:address;parameters”); • HTTP Connection • Connector.open(“http://www.mobilejava.co.kr”); • FTP Connection • Connector.open(“ftp://www.mobilejava.co.kr”); • Socket Connection • Connector.open(“socket://www.mobilejava.co.kr:5555”); • Datagram Connection • Connector.open(“datagram://address:port#”);
5-2. Connection 생성방법2 • Communicate with a Port • Connector.open(“comm:0;baudrate=9600”); • Open Files • Connector.open(“file:/myFile.txt”); • Network File System • Connector.open(“nfs:/10.1.7.1/myFile.txt”); • Infrared Connection • Connector.open(“irda://”);
6. 소켓을 이용한 무선 네크워크 프로그래밍 • 소켓 : 양방향통신에서의 종단점을 말함. • 무선장치와 원격서버 또는 무선 장치간에 가장 기본적인고 신뢰할 수 있는 low-level의 통신 방식임. • 유연성 있는 개발 환경 제공, • 단점: 특정장치에 제한 되어 사용, 이식성 낮음. • 통신방법은 송수신자가 각자의 소켓으로 연결되어 있어야 가능 . • 과정 • 1.Connector.open() 사용해 소켓 open한다. 2. 데이터 패킷 송수신위한 OutputStream, InputStream이 소켓 연결에서 생성 3.객체의 읽고 쓰는 메소드를 통해 데이터를 주고 받는다 4.종료전에 소켓 연결과 스트림을 닫는다
6-1. 소켓 통신 흐름도 Client 무선 장치 Client 무선 장치 80 port 에 socket 연결 Web Server Connector.open(:socket://127.0.0.1:80”) 서버에 index.html 열기 요청 dataOutputStream.writeChars(“Get/index.html\n”) 요청된 웹페이지 한글자씩 저장 inputchar=dataOutputStream.read())
7. 데이터그램을 이용한 무선 네트워크 프로그래밍 • Datagram은 비신뢰성 통신망이다. • 고정된 전용 커넥션이 없다. • 패킷 기반의 통신 방식 : packet-switched 무선망은 MIDP장치에서 이런 형식의 통신 지원함. • UDP : 데이터그램통신의 기반 • 단점: 특정장치에 제한적 사용, 이식성 낮음.
7-1. UDP • 기능 • 데이터그램 통신 기반으로 송신자가 수신자 정보(URL, port Number)를 보냄. • 데이터의 수신여부 보장 못함. 2. 사용 조건 : 데이터 전송의 정확성보다 속도가 중요할 때 주기적으로 정보를 전송할 경우 소켓통신이 지원되지 않을 경우
7-2. 데이터그램 사용하기 1. 데이터그램 커넥션을 맺는다 2. 보낼 메시지와 도착지 정보를 담은 데이터그램 객체를 생성 3. 데이터그램 메시지 전송 4. 미리 할당된 버퍼에 받은 데이터그램 객체를 생성 5. 맺어진 커넥션을 통해 데이터그램 버퍼를 사용하여 메시지 수신을 기다린다 6. 사용 후 데이터그램 커넥션을 닫는다.
7-4. Data Gram 규칙 • 지정된 패킷의 크기 벗어나면 안됨. : getMaximumLength()로 허용치 알 수 있으나 각 벤더별 차이 있음. • 데이터그렘의 헤더는 패킷의 크기가 클수록 안정적이고 전송율 높음. • 무선네트워크가 불안정하면 패킷이 유실될 수 있다. 패킷의 크기를 조절한다.
7-5. packet[패킷] • 데이터 전송에서 송신측과 수신측에 의하여 하나의 단위로 취급되어 전송되는 데이터의 묶음. 패킷의 크기는 수신측과 전송측에 의하여 사용되는 통신 규약에 의하여 결정이 되는데, 일반적으로 1KBit 또는 2KBit 이하의 크기가 사용되고 있다. • 패킷을 사용하는 데이터 통신에서는 송신측에 의하여 데이터와 데이터를 전송하는 데 필요한 제어 정보를 사용하여 하나의 패킷을 구성하여 통신망으로 전달한다. 이때 통신망에서는 패킷의 제어 정보를 사용하여 수신측의 위치 및 데이터 전송 경로 등을 확인하여 패킷이 정확한 위치에 전달되도록 중재한다.
7-6. 데이터그램 커넥션 1. DatagramConnection interface와 Datagram class 지원 • 데이터그램은 데이터그램 메시지 저장 공간 제공. • 데이터그렘 통신을 위해서는 먼저 데이터그램 커넥션을 연다. • DatagramConnection dc = (DatagramConnection)Connector.open(“datagram://localhost:9000”); //클라이언트 모드 • Port 반드시 필요, 호스트 이름이 없으면 “서버 모드”로 생성됨. • 클라이언트 모드는 데이터 송신만 가능하고, 보낼 데이터그렘에는 port번호와 host번호가 있어야 한다.
7-7. 데이터그램 흐름도 서버 포토 9001 통해 데이터그렘 연결 생성 Datagram Client Datagram Server Connector.open(“datagram://:9001) 클라이언트는 연결 생성 Connector.open(“datagram://:9000) 서버에 송신(클라이언트측), 데이터 수신(서버측) Dc.send(sendDatagram), dc.receive(receiveDatagram) 클라이언트에게 돌려줌 dc.receive(receiveDatagram);
8. HttpConnection이용한 무선 네트워크 프로그래밍 • 장점 • 모든 장치에서 지원 • 네트워크 의존적이 아니다-이식성이 좋다 • XML을 이용하면 다른 형태의 데이터를 쉽게 http 요청에 담아 보낼 수 있다
8-1. HttpConnection의 상태 • Setup상태 : 아직 서버에 연결되지 않은 상태 • Connected 상태 : 연결이 되어있는 상태로 파라미터들을 전송하고 응답할 수 있다. • Setup에서 전환하기: 데이터를 서버로부터 받거나 전송하는 메소드를 사용했을 때 발생
8-2. HttpConnection Request 메소드 • GET 전송방식 : 프로그램에서 지정한 url의 웹 문서의 내용을 가져올 때 사용. - 구성: httP 헤더정보 + MIME 타입정보+ 실제문서 • HEAD 전송방식 : 웹 문서의 정보만 얻어옴, • POST전송방식: URL이나 CGI 프로그램에 폼의 정보를 전송할 때 사용. • 차이점: post 방식은 stream을 이용해 전송하고 get방식은 querry string에 환경변수를 포함해 전송함.
8-3. Get 방식 • http://localhost/Servlets/Chapter9?request=gettime stamp • : querry string에 url에 포함됨. • Getquery ()메소드 사용하고, request=timestamp가 반환됨. • Get 방식으로 요청하면 이전의 환경변수와 그 값도 서버로 전송된다.
8-4.HEAD방식 • 정보 • Content-TYPE • Content-length • Content-encoding • Date • Last-modified • Expires(유효기간) • 사용처: 이런방식은 일반적으로 캐쉬정보를 계속 사용해도 되는지 변경해야 하는지를 결정할 때 사용 • setRequestMethod(HttpConnection.HEAD)메소드 사용해 사용방식 지정
8-5.POST 방식 • 이방식으로 HTTP request를 보내면 HttpConnection으로 부터 INputStream과 OUtputStream을 얻어야 한다. • InputStrem: 웹 서버에서 응답을 얻을 때 사용 • OutputStream: stream을 사용해 데이터를 분리해서 보낼 때 사용한다.
9-1. HTTP Connection (GET방식) (1) void getGrade() throws IOException { String url = "http://developer.java.sun.com/cgi-bin/getgrade.cgi?name=182016"; HttpConnection c = null; InputStream is = null; OutputStream os = null; StringBuffer b = new StringBuffer(); TextBox t = null; try { c = (HttpConnection)Connector.open(url); c.setRequestMethod(HttpConnection.GET); c.setRequestProperty("IF-Modified-Since", "10 Nov 2000 17:29:12 GMT"); c.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0"); c.setRequestProperty("Content-Language", "en-CA"); os = c.openOutputStream();