Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 63
Текст из файла (страница 63)
Whenthe reference count reaches zero, start a shutdown timer, using a CTimerclass. When the timer expires, close the server by stopping the activescheduler. If another session is opened while the timeout is in progress,cancel the timeout.11Symbian OS TCP/IP NetworkProgrammingThe ability to communicate data is a feature that differentiates smartphones from traditional voice-only mobile phones. Smartphones canconnect to a network through cellular technologies such as GPRS andEDGE and perform a variety of tasks normally associated with networkedPCs. Many phones also have Wi-Fi capability, allowing them to connectto a wireless Local Area Network (LAN).Here are just some of the smartphone applications made possible bydata communication:•browsing (HTML, WAP)•email•instant messaging•streaming media (mobile video services, etc.)•multiplayer network-connected games.The TCP/IP protocol suite is used for most networked services includingthe examples just given.
In fact, TCP/IP is the de facto standard forcommunicating on the Internet (it’s almost synonymous with the Internetitself), and is used in most private data networks as well.Symbian OS provides full TCP/IP networking support as well as asocket-based API to allow developers to write their own communicationsoftware. This chapter introduces TCP/IP on a Symbian OS device andshows how to use the socket API to write your own TCP/IP networkingapplications.
The most popular network API for programming in TCP/IPis the Berkley Unix (or BSD) C-based socket API and it is presented in thischapter for comparison (Symbian supports a version of it). The Symbian324SYMBIAN OS TCP/IP NETWORK PROGRAMMINGOS native C++ socket API is then presented, and compared with the BSDsocket API.Note that to call the Symbian OS network API functions discussed inthis chapter, your application will need the NetworkServices basiccapability.
Since this capability is in the basic user-grantable category,you can run the examples presented in this chapter without requiringthem to be Symbian Signed (you can simply ‘self-sign’ them with aself-generated certificate without having to request a Symbian Signeddeveloper certificate) to install and run on the phone. Reference Chapter 7for more information on platform security and Symbian Signed.We begin this chapter with a generic introduction to TCP/IP programming for those new to network programming.
If you are alreadyfamiliar with the general principles of TCP/IP and socket programming,you can skip the preliminary TCP/IP and BSD sections, and go directly tosection 11.3.At the end of the chapter is a comprehensive example that enables youto expand SimpleEx to retrieve the current temperature from a weathernetwork server and display it on the screen.11.1Introduction to TCP/IPTCP/IP refers to a suite of protocols as opposed to a single protocol(i.e., TCP over IP).
This protocol suite, sometimes referred to as theInternet Protocol Suite, serves as the foundation for communication onthe Internet, as well as most local networks. TCP/IP, like any othercommunication protocol suite, insulates network applications from theunderlying hardware and low-level software so that they can concentrateon sending and receiving application data over the network.Let’s look at the main protocols that are included in the TCP/IPsuite – TCP, UDP, and IP.
These protocols are the most important onesfor the network application programmer and are the ones that are coveredin this chapter.•TCP – Transmission Control ProtocolTCP is a transport-level, connection-oriented protocol and providesbuilt-in flow control for reliable transfer of data between networknodes. TCP is packaged and sent over the network layer IP protocol.TCP is the protocol most used by network applications and the web.•UDP – User Datagram ProtocolUDP, like TCP, is a transport-level protocol; however, UDP is connectionless and thus more lightweight than TCP.
UDP is basicallya ‘fire-and-forget’ protocol in that it does not provide any built-inconfirmation that the packet has arrived at its destination, nor doesit perform any retransmissions on errors, or handshaking of any kind.INTRODUCTION TO TCP/IP325UDP is used where speed is most important and it doesn’t matter if afew packets are lost.UDP is not as commonly used as TCP, except in programs (e.g.,multiplayer games) where speed is more important than reliability.UDP is also used for some network services, such as DNS (DomainName Service), which resolves a host name into an IP address.•IP – Internet ProtocolIP is the network-level protocol over which both TCP and UDP (aswell as other Internet suite protocols) are layered.
TCP and UDPpackets reside within the data area of an IP packet – like an envelopewithin an envelope. When a destination node receives an IP packet,it looks at a protocol field in the header to determine the protocol ofthe data it contains.IP is connectionless and data is transferred via packets that flowfrom a source to a destination.
IP defines how these packets arerouted and delivered from the source to the destination by the variousrouters and switches, using a quad byte address1 – known as the IPaddress – assigned to each communication point on the network. IPalso handles functions such as fragmenting large packets into multiplesmaller packets, and limiting the lifetime of a packet in the event ofa router setup problem (to avoid having a packet roaming around theInternet forever).At the application level there is seldom a need to deal with IPdirectly, applications use TCP and UDP instead.Figure 11.1 shows a simple diagram of TCP and UDP layered ontop of IP.TransportLayerTCPUDPNetworkLayerIPPhysicalLayerPhysical networkFigure 11.1 TCP, UDP, IP Layering1In the new IPv6 protocol, IP addresses consist of eight 16-bit values (128 bits), whichgreatly expands the addresses that are available from IPv4’s 32-bit addresses.
At the time ofwriting, IPv4 is still the dominant protocol though and is what this chapter assumes.326SYMBIAN OS TCP/IP NETWORK PROGRAMMINGAfter reading the descriptions of UDP and IP, you may wonder whatadvantages UDP provides over IP, since both are connectionless with noflow control built in. The answer is: not a lot. However, UDP adds a portaddress (as TCP does) to supplement the IP address and it includes a dataintegrity checksum (IP only checksums the IP header).11.1.1 IP Addresses and PortsIn both TCP and UDP, data is transferred between two endpoints ofa network. An endpoint is uniquely identified by the combination ofan IP address and a port address.
The IP address (which has the formxx.xx.xx.xx – e.g., 10.1.2.3) identifies a particular machine, and the portaddress (a 16-bit unsigned integer) – which specifies one of 65,536possible ports – identifies a particular endpoint on that machine.In the case of TCP, a virtual connection is first established between thetwo endpoints (via a special handshake), and data is then sent throughthis virtual connection.
In UDP, no virtual connection is established andpackets are simply sent from one endpoint to another.11.1.2 Client–Server Network ModelBoth TCP and UDP use a client–server model for network communications. A server provides a service, and makes it available to multipleclients (and this can be a very large number of clients), by creating anetwork endpoint with a well-known port address, and waiting at thatendpoint for a client request to use the service.
In the case of TCP, theserequests are connection requests to establish a virtual connection wherethe server and client can exchange data. In the case of UDP, it will simplyreceive packets from the client and process them on its behalf.11.1.3 Well-Known Server-Side Port AddressesSince clients initiate network connections, they must not only know theIP address of the server, but also the port number of the service on thatserver. To make this possible, services are assigned fixed port addresses,which are well known, so that a client always knows where to find aservice on a server.Below are some examples of network services, along with the portnumbers they use:ServiceEchoFTPTelnetHTTP/webPOP3 emailPort7212380110NETWORK PROGRAMMING USING SOCKETSServiceIMAP emailStreaming mediaDoomLandmark messaging327Port1435376663969Figure 11.2 illustrates an example of client–server network communications and shows the relation of IP and port addresses.NetworkServer 1 (xx.xx.xx.xx)Clientport 80Web serversoftwareport 110EmailClientServer 2 (xx.xx.xx.xx)Clientport 23port 537port 110TelnetStreaming mediaEmailClientFigure 11.2 Client and Server Communications11.1.4 Client-Side Port AddressesAlthough the server-side port addresses must be known so that the clientcan find the service, the port address on the client side does not generallyneed to be known.
This is because the server simply sends its responsesback to the IP address/port that sent it the data. Therefore, in most cases aclient endpoint is assigned a random unused port address by the operatingsystem (in the range 49,152–65,535 to avoid well-known port addresses).11.2 Network Programming Using SocketsThe goal of a good networking API is to hide the underlying details ofthe network and allow you to connect to a remote host and transfer data328SYMBIAN OS TCP/IP NETWORK PROGRAMMINGeasily. This section introduces the concepts of network sockets and howto program using them.The socket programming interface originated from BSD Unix as ageneric API for Inter-Process Communications. Since then it has becomethe standard for network programming.
Virtually all operating systemsthat support TCP/IP have some sort of socket API, including Symbian OS.A socket represents an endpoint of a communication path in a network.The endpoints are identified by a machine’s IP address in combinationwith a port address and the communication between them represents achannel. So a session between two nodes on a network consists of asocket pair – one socket for each end of the communication pipe.The socket API functions provide a generic interface for transferringdata between the two endpoint sockets, independent (for the most part)of the underlying protocols. The programmer creates a socket, establishesa connection with the remote endpoint (which is usually on anothermachine, but can also be on the same machine using the 127.0.0.1loop-back address), and then transfers data over the socket using readand write commands.11.2.1 Client–Server Socket FlowThe flow of creating and using a socket depends on whether you are onthe client or the server side, and whether you are using TCP or UDP.Here are the basic steps for creating and using a socket on the client andserver sides.Client-side code1.Create the client-side socket and get a handle to it.2.Connect the client socket to a destination endpoint.The socket must be connected to a destination endpoint for TCP butit is optional for UDP.A TCP connection is established between the endpoints byexchanging a set of packets to establish a virtual connection.Since UDP is connectionless, there is no handshaking betweenthe endpoints to establish a connection.