Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 31
Текст из файла (страница 31)
If youcannot immediately recognize your local address, you can try them all.One of the addresses is the address of your test server.SETTING UP THE DEVELOPMENT ENVIRONMENT163Environment B: Phone Internet access and a PC serverYou have to find out the server’s external IP address. Open a web browseron your server (PC) and go to one of the following websites:• http://checkip.dyndns.org• www.ip-address.com• http://whatismyipaddress.comWrite down the IP address that the site reports. This is the address ofyour test server.Environment C: Phone Internet access and an external test serverYou have probably seen the address of your server already. If you can login to the server using Secure SHell (SSH), you can use the address that isused by SSH for mobile development.Environment D: Phone Internet access and an external web serverYou probably have a domain name, such as www.mydomain.com,assigned to your server.
The service’s documentation should tell you howto update web pages at that address. You should be able to make a simpleHTML form containing one text input box and a simple script that handlesit on the server side.The script should return "Hello \$name" where \$name is the texttyped in the form. There are plenty of tutorials on the web showing howto do this using the web back end of your choice.
Once this works, youhave a test environment in place and you can proceed to Section 8.3.Testing the server in environments A, B and CNext we create a simple server script. The script waits for a new connection to be initiated. It then shows the client’s IP address and the first line inthe request. You need to execute this script on your PC (in environmentsA and B) or on your external server (environment C). The script waits forincoming connections in an infinite loop.
You can interrupt the server bypressing Ctrl-C.Example 69: Test serverimport SocketServerclass Server(SocketServer.TCPServer):allow_reuse_address = True164MOBILE NETWORKINGclass Handler(SocketServer.StreamRequestHandler):def handle(self):print "CLIENT IP %s:%d" % self.client_addressprint "Message: " + self.rfile.readline()server = Server((’’, 9000), Handler)print "WAITING FOR NEW CONNECTIONS.."server.serve_forever()Save the code above to the file testserver.py and execute it onthe command line using the command python testserver.py. Thisserver works in the same way in Linux, Mac OS X and Windows, giventhat you have Python installed on your PC.This test server uses some Python concepts, such as custom objects,which have not been introduced earlier in this book.
You can find moreinformation about creating objects, for example in the Python tutorial.However, for purposes of this book, you do not have to care about thedetails. Since this book is not about making Python software for servers,you can just skim through the following description. We use similarexamples on the server side later in this chapter, so basic understandingof this example is useful.The script is based on Python’s standard SocketServer object,which takes care of waiting for new incoming TCP connections.
Oncea connection has been established, SocketServer calls the givencallback function, which then handles the actual request.We modify one parameter, allow reuse address, in the standardserver. This modification makes it possible to re-use the same server portagain if the server is restarted. In the default case, a closed port has aquarantine period during which it cannot be re-used.The callback function must belong to a StreamRequestHandlerobject. The function is given one special parameter, self, that is used toaccess the object’s internal variables. self.client address containsthe client’s IP address and port in a tuple.
Data from the client is readfrom self.rfile, which acts like a file object, in a similar way to theserial object in the Bluetooth server in Example 60.The server object is created with two parameters in a tuple, the serverport (9000) and a reference to the Handler object. The server portshould correspond to the port which you have opened in your firewall.Examples in this chapter use port 9000, but you can use some other port.Note that port numbers below 1024 are reserved for registered services,so it is better to use a port number between 1025 and 65535.If you have a local firewall, you should allow all incoming connectionsto the port which you used above (for example, 9000). If you useenvironment B and you have an Internet router with NAT, you haveto enable port forwarding from the router to your PC, from and to theSETTING UP THE DEVELOPMENT ENVIRONMENT165port you specified above.
Port forwarding may require you to specify thelocal IP address of your PC. Follow the instructions for environment A tofind it.Once your server is up and running, that is, it says ‘WAITING FOR NEWCONNECTIONS’, you can try to connect to it. We test the connectionwith a normal web browser, first on the PC and then on your mobilephone. If it works with the browser on your phone, it will work withPyS60, too.First, open a web browser on your PC.
Type in your server’s address,which you found above, and specify the correct port. For example, alocal address might look like http://192.168.0.2:9000/. Whenyour browser tries to connect to the server, the server calls the requesthandler function handle(). The request handler then prints out theclient’s IP address and the first line of the HTTP request that the browsersent to the server.If you see some lines printed out by your server script, the connectionworks correctly. The browser shows just an empty page, or it may showan error, as the server does not respond to the request. If the server scriptdoes not print out anything, a firewall might be blocking the connectionor you may be trying to connect to the wrong IP address.
If you foundseveral possible IP addresses in environment A, try each of them until aconnection is established.After you have managed to establish a connection from your webbrowser on the PC to the server, you can try the same with your phone.Open the web browser on your phone and type in the server’s IP addressand port, exactly as on the PC.If the connection is established correctly, you should see some linesprinted out by the server script. If the connection works on your PC butnothing happens when you try to connect with your phone, there mightbe something wrong with the phone’s network settings in general.To find this out, try to connect to any well-known website, such aswww.google.com, with the phone’s browser.
If this succeeds, you have aworking Internet connection and the culprit is probably a local firewall.If you cannot connect to any site with your phone, you should set up theInternet connection properly on the phone first, following the instructionsgiven by your operator or service provider.If you can now connect from your phone to your server, you have aworking test environment. If you cannot, don’t feel desperate. After all,the culprit might be a firewall or a NAT which is just working as it should.You can find many troubleshooting guides on the web if you searchfor phrases such as ‘port forwarding tutorial’ or ‘firewall tutorial’. Notethat, in environments A and B, the IP address may change when your PCor router reboots. If your environment suddenly stops working, repeat thesteps above to find out the new address.166MOBILE NETWORKING8.3 Communication ProtocolsA communication protocol defines how to move data from place Ato place B.
Depending on the application, one has to balance severaldifferent factors, such as latency, addressing and data encoding, whenchoosing the best protocols for the task – no single protocol is suitable forall applications. The situation is similar to the transportation of physicalgoods. You have to choose the proper packaging, routing and mode oftransportation (air, ground or sea) for your cargo.Luckily, some common protocols are enough for almost all applications.
This chapter focuses on a stack of three protocols, depicted inFigure 8.2.Figure 8.2 Protocol stack used in this bookIt is likely that these protocols will serve all your needs for communication. Most of the Internet works on TCP and the web is built on top ofit using HTTP. For this reason, we use the terms ‘web server’ and ‘HTTPserver’ interchangeably.
The topmost protocol, JSON, is a recent additionto the stack and it is typically used by modern web applications.The protocols are complementary to each other: TCP is responsible forestablishing connections between two IP addresses and moving packetsbetween the two endpoints. Nowadays, HTTP is used as a common wayto access services (including web pages) behind URL addresses. It usesTCP to transfer data between the client and an HTTP server. JSON is usedto encode data structures, such as lists and dictionaries, in a string thatcan be sent easily over HTTP.Imagine that you want to move a list of integers, for instance thenumbers 1, 2, 3, from a PyS60 program to a web service.
This is depictedin Figure 8.3, where the dark line represents the steps for sending andreceiving the list; information on the highlighted rows is handled by theprotocol written in the corresponding position on the dark line. You startby encoding the list to a string using JSON. You pack the string in an HTTPrequest which is targeted at a specific URL. After this, the HTTP clientlibrary uses TCP to establish a connection to the server which hosts theURL and sends the HTTP request over the newly established connectionto the server.COMMUNICATION PROTOCOLSFigure 8.3167Sending data from a client to a server using the full JSON/HTTP/TCP protocol stackThe server unfolds the protocols one by one. First, it accepts theTCP connection, receives the HTTP request and finally it finds the JSONmessage in the request.