Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 25

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 25 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 252018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 25)

A datagram connection can be opened inclient or server mode. Client mode is for sending datagrams to a remotedevice. To open a client mode datagram connection we use the followingURI format:datagram://localhost:1234Here the port number indicates the port on the target device towhich the datagram will be sent. Sample code for sending a datagram isshown below:String message = “Hello!”;byte[] payload = message.toString();try{UDPDatagramConnection conn = null;conn = (UDPDatagramConnection)Connector.open(“datagram://localhost:1234”);Datagram datagram = conn.newDatagram(payload, payload.length);conn.send(datagram);}catch(IOException ioe){...}Server mode connections are for receiving (and replying to) incomingdatagrams. To open a datagram connection in server mode we use a URIof the following form:datagram://:1234114MIDP 2.0 AND THE JTWIThe port number in this case refers to the port on which the localdevice is listening for incoming datagrams.

Sample code for receivingincoming datagrams is given below:try{UDPDatagramConnection dconn = null;dconn = (UDPDatagramConnection)Connector.open("datagram://:1234");Datagram dg = dconn.newDatagram(300);while(true){dconn.receive(dg);byte[] data = dg.getData();...}}catch(IOException ioe){...}A signed MIDlet suite which contains MIDlets that open datagram connections must explicitly request the javax.microedition.io.Connector.datagram permission (needed to open client connections) andthe javax.microedition.io.Connector.datagramreceiverpermission (needed to open server connections) in its MIDletPermissions attribute, for example:MIDlet-Permissions: javax.microedition.io.Connector.datagram, ...or:MIDlet-Permissions: javax.microedition.io.Connector.datagramreceiver,...or:MIDlet-Permissions: javax.microedition.io.Connector.datagram,javax.microedition.io.Connector.datagramreceiver, ...If the protection domain to which the signed MIDlet suite wouldbe bound grants, or potentially grants, the requested permissions, theMIDlet suite can be installed and the MIDlets it contains will be able toopen datagram connections, either automatically or with user permission,depending on the security policy in effect.Whether MIDlets in untrusted MIDlet suites can open datagram connections depends on permissions granted to MIDlet suites bound to theuntrusted protection domain.3.3.4.6 Security Policy for Network ConnectionsThe connections discussed above are part of the Net Access functiongroup (see the Recommended Security Policy for GSM/UMTS CompliantMIDP 2.0115Devices addendum to the MIDP 2.0 specification).

On the Nokia 6600and Sony Ericsson P900/P908, MIDlets in untrusted MIDlet suites canaccess the Net Access function group with User permission (explicitconfirmation required from the user). On the Sony Ericsson P900/P908,the default User permission is set to session (and is not customizableby the user). On the Nokia 6600, the default User permission is set tooneshot, but can be changed by the user to session or disallowed.The Sony Ericsson P900/P908 supports the trusted protection domainon Organizer firmware versions R2B02 or later.

The security policyin effect for MIDlets in MIDlet suites bound to the trusted protectiondomain on the P900/P908 allows automatic access (Allowed permission)to the Net Access function group connections. At the time of writing, theavailable firmware release (3.42.1) on the Nokia 6600 only supported theuntrusted domain, although future releases will add support for trustedprotection domains.3.3.4.7 Practical Networking using Wireless NetworksIn the spirit of providing practical information, we shall now digressslightly into a discussion of networking on wireless data networks.

Themost common GSM networks at the time of writing are 2.5 G GeneralPacket Radio Service (GPRS) networks. GPRS networks can be regardedas a private sub-network behind a gateway to the Internet. All current GPRS network providers operate their consumer networks behindNetwork Address Translation (NAT) gateways and dynamically allocateprivate IP addresses to mobile terminals on each PDP activation (datasession).This has important consequences for application developers wishing touse wireless networking. One consequence is that mobile terminals on aGPRS network typically are unable to receive inbound connections sincetheir private IP addresses are not visible on the Internet. Another issuerelates to connection-less communications protocols such as UDP.

Whena terminal on a GPRS network sends a UDP packet to a remote host onthe Internet, the sender address is stripped out of the packet and replacedwith the IP address of the gateway and a port number representing theterminal data session. How long this session information remains valid(enabling the remote host to reply to the sender) depends on the NATgateway. After a limited period of time the gateway will re-allocate thatport to another GPRS terminal. Some NAT policies allow for the sessioninformation (and thus the allocated port) to remain associated with theGPRS terminal as long as traffic flows through it.

Such inactivity timeoutsthough, vary quite significantly between operators.The most effective way of avoiding complications arising out of operating behind NAT gateways is for developers to use TCP-based protocolssuch as HTTP. As long as there is an active TCP session in place, the116MIDP 2.0 AND THE JTWIgateway port will remain allocated to that GPRS terminal by the NATgateway, enabling two-way traffic between the GPRS terminal and theremote device.3.3.4.8 Socket Demo MIDletWe will finish this section with a simple example using TCP sockets tointerrogate a web browser. The Socket Demo MIDlet sends an HTTP GETrequest to a web server over a client socket connection and then reads anddisplays the response. The Socket Demo MIDlet consists of two classes,SocketMIDlet extending MIDlet and the ClientConnection class.The source code for the SocketMIDlet class is shown below.import javax.microedition.midlet.*;import javax.microedition.lcdui.*;public class SocketMIDlet extends MIDlet implements CommandListener {private final static String defaultURL ="socket://www.symbian.com:80";private Command exitCommand, sendCommand;private Display display;public TextBox textBox;public SocketMIDlet() {display = Display.getDisplay(this);exitCommand = new Command("Exit", Command.EXIT, 2);sendCommand = new Command("Send request", Command.SCREEN, 1);}public void startApp() {textBox = new TextBox("Sockets Demo", defaultURL, 256,TextField.ANY);textBox.addCommand(exitCommand);textBox.addCommand(sendCommand);textBox.setCommandListener(this);display.setCurrent(textBox);}public void commandAction(Command c, Displayable s) {if (c == exitCommand) {notifyDestroyed();}else if (c == sendCommand) {ClientConnection socketConn = new ClientConnection(this);socketConn.sendMessage(textBox.getString());textBox.removeCommand(sendCommand);}}public void pauseApp() {}public void destroyApp(boolean unconditional) {}}MIDP 2.0117SocketMIDlet sets up the UI and responds to the ‘‘Send request’’Command by creating an instance of ClientConnection and invokingits sendMessage() method, passing in a String representing the URLof the required web server.The main work is done in the ClientConnection class:import javax.microedition.io.*;import java.io.*;public class ClientConnection extends Thread {privateprivateprivateprivatefinal static String line1 = "GET /index.html\r\n";final static String line2 = "Accept: */*\r\n";final static String line3 = "Accept-Language: en-us\r\n";final static String line4 ="Accept-Encoding: gzip, deflate\r\n";private final static String line5 ="User-Agent: Mozilla/4.0 (Compatible; MSIE 5.01; Windows NT)\r\n";private SocketMIDlet sM = null;private String url = null;private String request = null;public ClientConnection(SocketMIDlet sM) {this.sM = sM;}public void sendMessage(String url) {this.url = url;String host = url.substring(url.lastIndexOf('/') + 1);System.out.println("host is " + host);String hostLine = "Host: " + host + "\r\n";request = line1 + line2 + line3 + line4 + line5 + hostLine;start();}public void run() {try{SocketConnection conn =(SocketConnection)Connector.open(url);DataOutputStream out = conn.openDataOutputStream();byte[] buf= request.getBytes();out.write(buf);out.flush();out.close();sM.textBox.insert("Finished request!\n" +"Receiving response...\n", sM.textBox.size());DataInputStream in = conn.openDataInputStream();int ch;while ( (ch = in.read()) != -1 &&sM.textBox.size() < sM.textBox.getMaxSize()) {String str = new Character((char) ch).toString();try {sM.textBox.insert(str, sM.textBox.size());}catch(Exception e) {e.printStackTrace();}118MIDP 2.0 AND THE JTWI}conn.close();conn = null;}catch(Exception e){e.printStackTrace();}}}The url parameter of the sendMessage() method has the following form:socket://www.symbian.com:80The sendMessage() method creates a GET request and then startsa new Thread to create the connection, send the request and read theresponse.

Let us look at the contents of the thread’s run() method inmore detail.SocketConnection conn = (SocketConnection)Connector.open(url);DataOutputStream out = conn.openDataOutputStream();byte[] buf= request.getBytes();out.write(buf);out.flush();out.close();A SocketConnection is opened using a URI of the formsocket://hostname:port and the returned SocketConnectionobject is used to get a DataOutputStream. After converting therequest to a byte array, this is written to the DataOutputStreamusing the write() method.

The flush() method is then called onthe DataOutputStream to ensure any buffered data is written to theconnection endpoint. This last step is essential. Symbian’s implementationof OutputStream buffers data internally and only writes it to theconnection endpoint when the buffer is full, or when the buffer is flushed.Failing to call flush() may result in data never being written to theconnection endpoint.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6353
Авторов
на СтудИзбе
311
Средний доход
с одного платного файла
Обучение Подробнее