qt fundamentals networking - mobile devices: mobile...

9

Upload: lynguyet

Post on 30-Mar-2018

225 views

Category:

Documents


2 download

TRANSCRIPT

1

Qt Fundamentals: Networking

5

Mobile Networking

� Many available network interfaceso WLAN (802.11b/g)o Bluetootho Infraredo Cellular (GPRS, UMTS, HSDPA, etc.)o USBo etc.

� Depending on the technology, several layers are already specified. I.e. Bluetooth specify everything up until the transport layer.

mobile = wireless?

6

Networking Applications on Mobile devices

When developing networking application for mobile devices there are a number of considerations that need to be taken into account e.g.:� Which technologies are available / what to use?

o Power consumption (battery capacity)o Speed / throughputo Rangeo Topology

Power consumption is becoming an important feature and selling point for new applications.

7

Networking Applications on Mobile devices

Profiling application performance:

Nokia Energy Profiler (currently Symbian only)

http://bit.ly/7mV7N

8

802.11 basics

� 802.11bo 2.4 GHz ISM-band o Up to 11 Mbps

� All use CSMA/CA for

multiple access� All have infrastructure

mode and ad hoc network version.

� 802.11go 2.4 GHz ISM-band o Up to 54 Mbps

� 802.11ao 5 GHzo Up to 54 Mbps

9

802.11 basics

10

802.11 basics Ad hoc

Infrastructure

� No routing but multihop possible

� Distributed beacon� Direct

communiction

� Connected to Distribution System (DS) usually the Internet

� Packets first go to the AP and then to the nodes

11

802.11 basics

� It is important to note that how data rates are selected is implementation specific. o According to the

802.11 spec. implementers are free to decide what speed to use.

source: www.bb-elec.com/bb-elec/literature/tech/wireless_basics.pdf

� Practice show very varying results. Especially for broadcast.

12

CSMA/CA for Broadcast

Carrier Sence Multiple Access with Collision Avoidance

14

Bluetooth

� Currently no support for Bluetooth in Qt however access can be obtained using 3rd party modules.

http://wiki.forum.nokia.com/index.php/QBluetooth_-_A_Qt_bluetooth_library

15

Infrared

As with Bluetooth no Qt API currently exist to use Infrared on devices.

IR data transmission is also employed in short-range communication among computer peripherals and personal digital assistants. These devices usually conform to standards published by IrDA, the Infrared Data Association.

� IR does not penetrate walls and so does not interfere with other devices in adjoining rooms.

� Point-to-point (quite sensitive) � Infrared is the most common way for remote controls to

command appliances.

16

CellularSource: http://en.wikipedia.org/wiki/Comparison_of_wireless_data_standards

� Large number of cellular networks available.

� Type will depend on users subscription.

17

USB

Not a wireless standard, but that brings a number of advantages on its own� Reliable data transfer� Charge while connected

Usually communication occurs over a serial-port emulation. E.g. on Linux using the usbserial module

19

IP (Internet Protocol)

The Internet Protocol (IP) is a protocol used for communicating data across a packet-switched internetwork using the Internet Protocol Suite, also referred to as TCP/IP.

Two version exist:� IPv4 � IPv6

Most significant change between IPv4 and IPv6 is the change from 32-bit addresses to 128-bit - i.e. from 4 billion available addresses to 340 undecillion.

20

� Source and destination addresses � IPv4 supports fragmentation � IPv6 no fragmentation (upper layer protocols must

accommodate this) � IPv6 is in general

simplified and pushes responsibility to upper layer protocols.

IP (Internet Protocol)IPv4 fields not present in IPv6 written in gray

21

Practical Issue: Fragmentation

� Fragmentation and broadcasto Avoid it by limiting the packet size

o Typical Maximum Transfer Unit (MTU) 1500 bytes (from Ethernet)

o Remember to account for headers in lower layers e.g. UPD 8 bytes + IP 20 bytes + 802.11 MAC header X bytes

fe = frame error probabilityps = packet successn = number of fragmentsps = (1-fe)n

22

Getting an IP Address (IPv4)

Every host and router on the Internet has an IP address. However, due to the limited amount of IPv4 addresses these are normally not global, but assigned using one of the following

mechanisms:� Dynamic Host Configuration Protocol (DHCP) allows a

computer to be configured automatically, eliminating the need

for intervention by a network administrator.� Local Link Address is a method by which a host may

automatically configure an interface with an IPv4 address in

the 169.254/16 prefix.� Static IP denotes that a host has manually been assigned the

IP address to use.

23

Broadcasting

� Unicast: one process talking to another process � Anycast: allows addressing one "closest" system (work in

progress)� Multicast: addressing an group of receivers� Broadcast: addressing all receivers on a specific network

1.Subnet-directed broadcast for the subnet 192.168.42/24, then 192.168.42.255 would be the subnet-directed broadcast

� Limited broadcast 255.255.255.255 - datagrams sent to this address must never be forwarded.

24

Unicast versus Broadcast

� To receive datagrams a node must BIND to a port

25

MulticastIPv4 multicast addresses: 224.0.0.0 through 239.255.255.255� To receive must explicitly join group (not necessary to send)

27

Socket Interface

� Originated in BSD Unix � One of the most widely-supported internet programming

interfaces today� A socket is an application-to-application channel

o UDP and TCP protocols accepted � A unique end-point is specified using the {ip address, port}

tuple. Qt provides a C++ object oriented API over the standard BSD socket interface.

28

UDP uses a simple transmission model without:� hand-shaking � reliability� ordering

UDP's stateless nature is also useful for servers that answer small queries from huge numbers of clients. Unlike TCP, UDP is compatible with packet broadcast (sending to all on local network) and multicasting (send to all subscribers).

UDP (User Datagram Protocol)

Datagram oriented

29

UDP (User Datagram Protocol)

Qt provides access to the UDP protocol through the QUdpSocket class.

Sender (minimum requirements)

Receiver (minimum requirements)

udpSocket = new QUdpSocket(this);

udpSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, 45454);

udpSocket = new QUdpSocket(this);udpSocket->bind(45454, QUdpSocket::ShareAddress);

connect(udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));

Operations:� read� write� bind

30

TCP (Transport Control Protocol)

For many types of applications the unreliable data deliver semantics provided by UDP is insufficient. For these applications TCP provides a connection-oriented communication. � Reliable using retransmissions� Flow control / Congestion control � Ordered data transfer� Data integrity guarantee using checksum. � Client-server oriented protocol � Stream oriented

31

TCP (Transport Control Protocol)

Qt provides access to the TCP protocol through the QTcpSocket and QTcpServer classes

32

TCP (Transport Control Protocol)

A TCP server Example:

� The TCP server consist of a QTcpServer that listens to port 55555o Generates a newConnection signal

Server::Server(QObject parent = 0) : QObject(parent)

{ m_tcpServer = new QTcpServer(this);

connect(m_tcpServer, SIGNAL(newConnection()),

this, SLOT(newConnection()));

m_tcpServer->listen(QHostAddress::Any, 55555);

}

33

TCP (Transport Control Protocol)

A TCP server Example:

� The next connection is retrieved using nextPendingConnection()

void Server::newConnection()

{ QTcpSocket *connection = m_tcpServer->nextPendingConnection(); connect(connection, SIGNAL(disconnected()), connection, SLOT(deleteLater()));

QByteArray buffer; QDataStream out(&buffer, QIODevice::WriteOnly);

out.setVersion(QDataStream::Qt_4_6);

QString greeting = QString("Hello! The time is %1").arg(QTime::currentTime().toString());

out << (quint16)0; out << greeting; out.device()->seek(0);

out << (quint16)(buffer.size() - sizeof(quint16));

connection->write(buffer);

connection->disconnectFromHost();}

34

TCP (Transport Control Protocol)

A TCP client Example:

� Use a QTcpSocket to connect to the hosto readyRead() is necessary, but there are more signals

that are interested, e.g. error

Client::Client(QObject *parent = 0) : QObject(parent){

m_tcpSocket = new QTcpSocket(this);

connect(m_tcpSocket, SIGNAL(readyRead()),

this, SLOT(readyToRead()));

m_tcpSocket->connectToHost(QHostAddress::LocalHost, 55555);

}

35

TCP (Transport Control Protocol)

A TCP client Example:� Use a QTcpSocket to connect to the host

o readyRead() is necessary, but there are more signals that are interested, e.g. error

void Client::readyToRead()

{ QDataStream in(m_tcpSocket); in.setVersion(QDataStream::Qt_4_6);

if(m_tcpBlockSize == 0) { if(m_tcpSocket->bytesAvailable()<sizeof(quint16))

return; in >> m_tcpBlockSize; }

if(m_tcpSocket->bytesAvailable() < m_tcpBlockSize) return;

QString greeting; in >> greeting; doSomething(greeting);

m_tcpBlockSize = 0;} 36

TCP (Transport Control Protocol)

� The protocol demonstrated is very basico Reply to all connections, then close

� A real world protocol would probablyo Keep the connection open and use a set of commands for

requesting and manipulating datao Carry some sort of versioning information etc.

37

Encrypted Sockets

� TCP/IP traffic is easy to overhear� QSslSocket provides encrypted TCP sockets

o Use connectToHostEncryptedo When receiving the encrypted() signal the connection is

encrypted.

� SSL, Secure Sockets Layer, is a layer on top of TCPo Relies on CAs � Certificate Authorities

39

QIODevice

QIODevice is the base for all I/O devices used in Qt� A typical I/O devices supports reading and writing blocks of

data� QIODevice provides an abstract interface to allow device

independent I/O features. Using the QIODevice:� Make sure the device is open (e.g. use isOpen()) using the open() function. Remeber to use the correct OpenMode (ReadWrite, ReadOnly, ...)

� Write to the device using write() or putChar()� Read from the device using read(), readLine(), or readAll()

� Call close() when finished 40

QIODevice

Reading from a QIODevice� QIODevice emits readyRead() when new data is

available for reading, e.g. when data is read from the network or microphone.

� The bytesAvailable() function can be used to check the number of bytes ready to be read.

Writing to a QIODevice � After writing to a QIODevice the bytesWritten() signal

is emitted. Note, that concrete implementations of QIODevice may provide their own signals and slots (providing redundant functionality).

41

QDataStream

The QDataStream class provides serialization of data to a QIODevice� Using QDataStream we can serialize data in a platform

independent manner.o Byte order etc.

QFile file("file.dat");file.open(QIODevice::WriteOnly);

QDataStream out(&file); // we will serialize the data into the fileout << QString("the answer is"); // serialize a stringout << (qint32)42; // serialize an integer

QFile file("file.dat");

file.open(QIODevice::ReadOnly);QDataStream in(&file); // read the data serialized from the fileQString str;qint32 a;

in >> str >> a; // extract "the answer is" and 42

Write

Read

42

QDataStream

Sending my custom types over the network

struct DataHeader{

bool m_raw QString m_filename;

bool isRaw() const { return m_raw; }

void setRaw(bool isRaw)

{ m_raw = isRaw; }

const QString& filename() const

{ return m_filename; }

void setFilename(const QString &filename)

{ m_filename = filename; }

QByteArray toByteArray();

};

/** * Data stream operators for serializing / deserializing a packet */

inline QDataStream& operator<<(QDataStream &stream, const DataHeader &packet){ stream << packet.m_raw;

stream << packet.m_filename;

return stream;

}

inline QDataStream& operator>>(QDataStream &stream, DataHeader &packet)

{ stream >> packet.m_raw; stream >> packet.m_filename;

return stream;}

QByteArray b;

QDataStream outStream(&b, QIODevice::WriteOnly);

DataHeader outHeader;

outHeader.setRaw(true);outHeader.setFilename("woops.txt");outStream << outHeader;

QDataStream inStream(b); // Opens in ReadOnly

DataHeader inHeader;inStream >> inHeader; // Data now read into inHeader

43

Endianness (byte order)

All the examples refer to the storage in memory of the value 0A0B0C0Dh. � Big-endian (MSB)

� Little-endian (LSB)

Network byte order

45

Application Layer Protocols

� QNetworkAccessManager provides an interface for sending HTTP requests and receiving responseso QtWebKit provides support for rendering HTML in your

applications. � QFtp implements client side FTP

There are many other protocols built on top of TCP/IP, e.g. BitTorrent, SMTP, POP, IMAP, SSH, TELNET, TFTP, etc.

Replaces QHttp

46

Example: Downloader

class Download : public QObject{ Q_OBJECTpublic:

Download() { connect(&manager, SIGNAL(finished(QNetworkReply*)),

this, SLOT(finished(QNetworkReply*))); }

void download(const QUrl &url) { manager.get(url);

} private slots:

void finished(QNetworkReply *reply) { reply->deleteLater();

emit done(reply->url(), reply->readAll()); } signals:

void done(const QUrl &url, const QByteArray &data); private:

QNetworkAccessManager manager;};

Possible improvements:� Handle error conditions� Handle authentication

challenges� Handle SSL � Use application supplied

QNetworkAccessManager

48

Service Discovery

� An essential part of building a Local Area Networking (LAN) application

� Bluetooth uses the Bluetooth Service Discovery Protocol

(SDP) part of all Bluetooth implementations.o In practice can be quite slow.

� For IP-based networks several solutions exist:o Simple Service Discovery Protocol (SSDP) used in UPnPo DNS Service Discovery (DNS-SD) used in Zeroconf (also

know as Avahi and Bonjour)

49

Service Discovery

� From a usability point of view service discovery should be a part of any application. o E.g. asking a user to enter the IP address of his/her

network enabled printer is unacceptable. � Goal: all services on a network should be discoverable and

easily accessed.� Challenges: keeping the protocol simple and efficient while

still supporting future services.