Docsity

Networked Applications: Server Architectures and Protocols, Papers of Computer Science

Toggle sidebar
bg1
Java Prog. Techniques for Games. Chapter 18. Net Basics Draft #1 (16th June ‘03)
1 Andrew Davison. 2003
Chapter 18. Networking Basics
The next four chapters are about networked games.
This chapter runs through networking fundamentals (e.g. what are the client/server
and peer-to-peer models?) and explains basic network programming with sockets,
URLs, and servlets
Chapter 19 is about online chat, the “hello world” of network programming. We look
at three chat variants: one using a client/server model, one employing multicasting,
and chatting with servlets.
Chapter 20 describes a networked version of the FourByFour application, a turn-based
game which is a demo in the Java 3D distribution.
Chapter 21 revisits the Tour3D application of chapter ?? (the robot walking about a
checkboard landscape), and adds networking to allow multiple users to share the
world. We also discuss some of the advanced issues concerning networked virtual
environments (NVEs), of which NetTour3D is a simple example.
The structure of this chapter in more detail:
• descriptions of the core attributes of network communication;
• explanations of IP, UDP, TCP, network addresses, and sockets;
• overviews of the client/server and peer-to-peer models;
• four small client/server applications (sequential, threaded, nonblocking
multiplexing, and UDP multiplexing);
• a small peer-to-peer application (UDP multicasting);
• the problem of firewalls, leading to URLs and servlets for HTTP tunneling;
• a brief word about some other kinds of Java networking (RMI, Jini,
JavaSpaces, the Java Shared Data Toolkit).
1. The Elements of Network Communication
Network communication is often characterized by five attributes:
1) Topology
2) Bandwidth
3) Latency
4) Reliability
5) Protocol.
1.1. Topology
Topology is the interconnection ‘shape’ of machines linked over a network.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c

Partial preview of the text

Download Networked Applications: Server Architectures and Protocols and more Papers Computer Science in PDF only on Docsity!

Chapter 18. Networking Basics

The next four chapters are about networked games.

This chapter runs through networking fundamentals (e.g. what are the client/server and peer-to-peer models?) and explains basic network programming with sockets, URLs, and servlets

Chapter 19 is about online chat, the “hello world” of network programming. We look at three chat variants: one using a client/server model, one employing multicasting, and chatting with servlets.

Chapter 20 describes a networked version of the FourByFour application, a turn-based game which is a demo in the Java 3D distribution.

Chapter 21 revisits the Tour3D application of chapter ?? (the robot walking about a checkboard landscape), and adds networking to allow multiple users to share the world. We also discuss some of the advanced issues concerning networked virtual environments (NVEs), of which NetTour3D is a simple example.

The structure of this chapter in more detail:

  • descriptions of the core attributes of network communication;
  • explanations of IP, UDP, TCP, network addresses, and sockets;
  • overviews of the client/server and peer-to-peer models;
  • four small client/server applications (sequential, threaded, nonblocking multiplexing, and UDP multiplexing);
  • a small peer-to-peer application (UDP multicasting);
  • the problem of firewalls, leading to URLs and servlets for HTTP tunneling;
  • a brief word about some other kinds of Java networking (RMI, Jini, JavaSpaces, the Java Shared Data Toolkit). 1. The Elements of Network Communication

Network communication is often characterized by five attributes:

  1. Topology
  2. Bandwidth
  3. Latency
  4. Reliability
  5. Protocol.

1.1. Topology

Topology is the interconnection ‘shape’ of machines linked over a network.

Popular shapes are the ring, star, and all-to-all, illustrated in Figure 1.

Figure 1. Some Network Topologies.

Choosing the best topology for an application is a complicated matter, depending on many network characteristics, such as bandwidth and latency, and the particular communication patterns inherent in the system.

The star topology, present in client/server applications, is the most popular, while the all-to-all topology appears (in modified forms) in peer-to-peer systems.

1.2. Bandwidth

Bandwidth is the rate at which the network can deliver data from a sender to the destination host. Modems can typically deliver 14,400-56,000 bits/second (14.4 – 56 Kbps), Ethernet can attain 10-100 Mbps (million bits/second), with newer technologies offering 1 Gbps (gigabits/second). Fiber optic cable exhibits speeds of up to 10 Gbps.

Dial-up usage is declining in the US, but 66.2% of users still connect with modems. According to March 2003 figures from Nielsen/NetRatings (http://www.nielsen- netratings.com/), 53.26% use 56 Kbps modems, 9.79% have 28/33.3 Kbps, and 3.17% are stuck with 14.4 Kbps modems.

A study by MetaFacts (http://www.metafacts.com/) showed that the vast majority of the 25,000 people they surveyed still utilize low-speed internet access; only 9% have DSL and 16% use cable modems. However, almost half of the narrowband users were considering an upgrade and, if current rates of uptake continue, broadband will be more widespread than dial-up by 2005.

More details can be found in the article:

“Your Speed May Vary” Robyn Greenspan, April 25th, 2003

host

host

host4 host

host

host

host

host4 host

host5 (^) server

host

host

host4 host

host

Ring Topology (^) Star Topology

All-to-All Topology

1.3. Latency

Latency is the amount of time required to transfer a bit of data from one place to another (typically from one player’s machine to another). In a MMORPG (Massively Multiplayer Online Role-Playing Game), latency exhibits itself as the delays when two players are interacting (e.g. shooting at each other); the goal is to reduce latency by as much as possible.

Most latency can be accounted for by the modems involved in the network: typically each one adds 30-40 ms to the latency. A client/server system may involve four modems between the sending of a message and its reception by another user: the sender’s modem, the modem inbound to the server, the modem outbound from the server, and the receiver’s modem, resulting in a total latency of perhaps 160 ms.

Another major contributor, especially over the internet, are routers, which may easily add hundreds of milliseconds. This is due to their caching of data before forwarding it, and delays while a router decides where to send a message. Routers may drop data when overloaded, which can introduce penalties in the 400-500 ms range for protocols like TCP which detect lost data and resend it.

Another issue is the speed of light – games would certainly benefit if it was faster! A message sent from the east to west coast of the US must take about 20 ms to get there. In general, about 8 ms of travel time are added for each time zone that a message passes through.

Designers often incorporate tolerances of 250 ms into the communication models used in games. A key observation is that most games do not require complete synchronization between all the players all the time. Synchronization is usually important only for small groups of players (e.g. those in close proximity inside the game world), and even then only at certain moments.

This relaxing of the synchronization requirement opens the door to various approaches based on temporarily ‘guessing’ information about other players. For instance, the game running on the user’s machine estimates other players’ current positions and velocities, and corrects them when the correct data arrives over the network.

Another implementation strategy is to decouple general game play from the networking side of the application. A separate thread (or process) waits for incoming data, so the rest of the application can continue unaffected.

Latency is essentially a WAN or internet issue; applications running over a LAN rarely need to consider latency, which may total less than 10 ms.

1.4. Reliability

Increased network reliability may increase latency time. For example, the possibility that a message may be lost while travelling over the network, led to the development of the TCP protocol which deals with data loss by resending. The disadvantage is that the actual arrival time of a message can be increased significantly, so impacting latency.

A desire to measure reliability has led to more complex checking of data based on cyclic redundancy checks (CRCs), which add further overheads.

An alternative view is to live with a certain degree of unreliability, reducing overheads as a consequence. Many forms of internet-based multimedia, such as streaming audio and video, take this line because losing small amounts of data only means a momentarily loss in sound or picture quality. The rapid transmission of the data is a more valued attribute.

1.5. Protocol

A protocol is a notation for specifying the communication patterns between the components of a networked application.

Different protocols support different capabilities, with the choice of protocol depending on many factors, such as the type of data being transmitted, the number of destinations, and the required reliability.

Most gaming application uses multiple protocols: one for data, another for control, and perhaps others specialised for particular types of data such as audio or video.

Different protocols exist for different levels of communication, which are defined in the ISO OSI model (see Figure 2).

Figure 2. The ISO OSI Model

A protocol suite is a collection of related protocols for different layers of the OSI model. The most popular is TCP/IP, originally developed by DARPA in the early 1980’s. Its wide popularity stems from it being implemented on everything from PCs to supercomputers, not being vendor specific, and its suitability for all kinds of network, from LANs up to the internet.

7 6 5 4 3 2 1

high-level protocol

low-level protocol

Application Presentation Session Transport Network

Data Link Physical

The IP protocol is currently in transition from version 4 to version 6 (IPv6), which supports 128-bit addresses, a simpler header, multicasting, authentication, and security elements. Java supports both IPv4 and IPv6 through its InetAddress class.

The transport layer delivers datagrams between transport end-points (machine ports) for any two machines on the Internet. An application’s location is specified by the IP address of its host, and the number of the port where it is ‘listening’. A port number is a 16-bit integer.

The TCP/IP transport layer protocols are:

  • UDP: the User Datagram Protocol
  • TCP: the Transmission Control Protocol

UDP is a connectionless transport service: a user message is split into datagrams and each datagram is sent along an available path to its destination. There is no (expensive) long-term, dedicated link created between the two systems. UDP inherits the drawbacks of the IP protocol: datagrams may arrive in any order, and there is no guarantee that a datagram will arrive. UDP is often compared to the postal service.

TCP is a connection-oriented transport service. From the user’s point of view, a long- term, dedicated link is set up between the sender and receiver, and two-way stream- based communication then becomes possible. For this reason, TCP is often compared to the telephone service.

However, the ‘dedicated’ link is implemented on top of IP, and so packets of information are still being sent, with the chance of reordering and loss. Consequently, TCP employs sophisticated error-checking internally to ensure that its component TCP datagrams arrive in the order they were sent, and that none are lost. This overhead may be too severe for gaming applications which value low latency.

Both UDP and TCP use a socket data structure to represent an end-point in the communication. For UDP, the socket is something like a mailbox, while a TCP socket is more like a telephone.

Java supports both TCP and UDP. A programmer uses the Socket class for creating a sender’s TCP socket, and the ServerSocket class for the recipient. Java offers the DatagramSocket for both sides of UDP communication, and a DatagramPacket class for creating UDP packets.

2. The Client/Server Model

The client/server model is the most common networking architecture employed in distributed applications. A server is a program (or collection of cooperating programs) which provides services and/or manages resources on the behalf of other programs, known as its clients. Figure 4 shows a typical client/server environment.

Figure 3. A Simple Client/Server

A key advantage of the client/server approach is the ability for the server to control its clients, by localising important processing and data within itself. For example, in online games, decisions about the outcome of a player’s actions (e.g. the shooting of a monster) will be made by the server. The alternative is to delegate this to the client’s application which may lead to abuse by hackers.

A central location for client data and processing makes it easier to monitor users, administer them, and charge them for game playing. These are significant benefits for commercial multiplayer gaming.

The server is an arbiter for conflicting client requests. For instance, it is impossible for two clients to update the same data state at the same time.

Placing state information in one place makes changing it straightforward, and avoids inconsistencies arising when updating multiple copies stored on clients.

Concentrating processing on the server-side permits the client side to run on a less powerful machine, an important consideration for network applications on PDAs or phones.

Concentrating most of the application in the server makes it is easier to maintain and update, compared to trying to upgrade code spread over a large, possibly non- technical, user base.

The main disadvantage of a ‘fat’ server is the potential for it to become a bottleneck, overloaded by too many clients, increasing latency to unacceptable levels. Excessive numbers of clients may also overload the server’s data storage capabilities.

Another significant issue is reliability – if the server fails then everyone will be affected. Almost as bad as failure is the (temporary) non-availability of the server,

Many of the killer apps of the 1980’s, such as telnet and e-mail, were client/server based but their usage patterns were symmetric – most machines ran both clients and servers. Usenet is a P2P application: it employs a decentralized file sharing model for distributing news, but an unofficial backbone has developed over time, based around server inequalities in storage capacity, processing speeds, and network connectivity.

Things started to change with the growth of the Web. It is a client/server model like most of the earlier applications, but differences lie in its political and social components.

Most users only browse the Web, they don’t run their own Web servers. This is due to their lack of technical knowledge, the difficulty of setting up a server, and because commercial ISPs do not allow them. Many ISPs only allocate dynamic addresses to clients making the running of servers impossible, and impose firewall restrictions which only permit Web page access. Broadband connections, such as cable modems, offer asymmetric bandwidth which makes the serving of material slow.

The restrictions on users (e.g. firewalls) are quite recent, triggered by the lack of accountability mechanisms in the internet protocol: there are no technological barriers to users sending spam, and attacking machines. The original designers made the fatal assumption that users are responsible! The problem is sometimes called “the Tragedy of the Commons”: a commonly owned resource will be overused until it degrades, due to the users putting self-interest first.

The issue of accountability has led to better support for cryptography in IPv6, and experimental technologies such as micropayments and reputation schemes.

With micropayments, a person wishing to use someone else’s resource (e.g. one of their files) must compensate that person in some way. This might be in the form of digital money or another valuable resource. Micropayments have the benefit of solving many forms of hacker attack, such as spam and distributed denial of service, since the hacker must pay an excessive amount in order to ‘flood’ the network with their datagrams.

A reputation scheme typically requires a respected user to verify the reliability of a new user. This idea is well-known in Java which utilizes encrypted signatures and third party verifiers to make trusted applets.

Many P2P systems are concerned with anonymity, so that external agencies cannot know who is involved in a P2P group, where files are stored, and who has published what. These aims make accountability and trust harder to support.

Part of the drive behind these systems is the case of Napster, which was effectively closed down because of its publication of music files that it hadn’t authored. Napster could be targeted because it was a hybrid of P2P and client/server: a Napster server stored details about who was logged on, and the published files. Unfortunately, this is a common situation – most current P2P systems require some server capabilities. For instance, games must validate new players, maintain account information, supply current status information for the game, and notify other users when a player joins or leaves.

Pure P2P has the advantage that there is no central point (no server) whose demise would cause the entire system to stop. This makes P2P resistant to some forms of attack, such as distributed denial of service and legal rulings!

The main drawback of P2P is paradoxically its lack of a server, which makes it difficult to control and manage the overall application.With no server, how does a new user discover what is available?

The P2P diagram in Figure 4 suggests that participants use broadcasting to communicate, but this approach soon consumes all the available bandwidth, for reasons outlined earlier. Large scale P2P applications use IP multicasting with UDP packets, which currently relies on the MBone, a virtual overlay installed on the internet to facilitate multicasting. A special pseudo-IP address, called a multicast IP address or class D address, is employed, which can be in the range 224.0.0.0 to 239.255.255.255 (though some addresses are reserved).

Multicasting avoids the potential for loops and packet duplication inherent in broadcasting, since it creates a tree-based communication pattern between the multicast group members. Java supports IP multicasting with UDP.

The Java Media Framework (JMF) is an API extension to Java for handling time- based media, specifically streaming audio and video (see http://java.sun.com/products/java-media/jmf/). The underlying protocol is RTP (the Real-Time Transport Protocol), implemented on top of UDP. Many networked multimedia systems use RTP and multicasting.

JXTA provides core functionality so that developers can build P2P services and applications (see http://www.jxta.org/). The core JXTA layer includes protocols and building blocks to enable key mechanisms for P2P networking. These include discovery, transport (e.g. firewall handling and limited security), and the creation of peers and peer groups.

The JXTA specification is not tied to any particular programming language or platform/device. Its communication model is general enough so that it can be implemented on top of TCP/IP, HTTP, Bluetooth, and many other protocols. Currently JXTA utilizes Java; it was initiated at Sun Microsystems by Bill Joy and Mike Clary. A good site for finding out about P2P is O’Reilly’s http://www.openp2p.com/.

4. Client/Server Programming in Java

The four examples in this section have a similar structure: the server maintains a high scores list (similar to the list in the arcade game of chapter ??), and the clients read and add scores to the list. The four variants of this idea are:

  1. A client and sequential server. The server can only process a single client at a time. The TCP/IP protocol is utilized.
  2. The same client, same protocol as (1), but the server is threaded enabling it to process multiple clients at the same time. Synchronization issues arise because the high score list may be accessed by multiple threads at the same time.
  3. The same client, same protocol as (1) and (2), but Java’s NIO is used to implement a multiplexing server without the need of threads.

The UML diagrams for the various classes are given in Figure 6. Only the public methods are shown.

Figure 6. UML Classes for the Client and Sequential Server.

A HighScores object manages the high scores list, with each name/score pair held in a ScoreInfo object.

The ScoreServer Class

The constructor for the ScoreServer creates the ServerSocket object, then enters a loop which waits for a client connection by calling accept(). When accept() returns, the server processes the client, then goes back to waiting for the next connection.

public ScoreServer() { hs = new HighScores(); try { ServerSocket serverSock = new ServerSocket(PORT); Socket clientSock; BufferedReader in; // i/o for the server PrintWriter out;

while (true) { System.out.println("Waiting for a client..."); clientSock = serverSock.accept(); System.out.println("Client connection from " + clientSock.getInetAddress().getHostAddress() );

// Get I/O streams from the socket in = new BufferedReader( new InputStreamReader( clientSock.getInputStream() ) ); out = new PrintWriter( clientSock.getOutputStream(), true );

processClient(in, out); // interact with a client

// Close client connection clientSock.close(); System.out.println("Client connection closed\n"); hs.saveScores(); // backup scores after client finish

} } catch(Exception e) { System.out.println(e); } } // end of ScoreServer()

The server-side socket is created with the ServerSocket class:

ServerSocket serverSock = new ServerSocket(PORT);

The waiting for a connection is done via a call to accept():

Socket clientSock; : clientSock = serverSock.accept();

When accept() returns it instantiates the rendezvous socket, clientSock.

clientSock can be used to retrieve client details, such as its IP address and host name.

The input stream is a BufferedReader to allow calls to readLine(). Since client messages end with a newline, this is a convenient way to read messages. The output stream is a PrintWriter, allowing println() to be employed. The stream’s creation includes a boolean to switch on autoflushing so there is no delay between printing and actual output to the client.

in = new BufferedReader( new InputStreamReader( clientSock.getInputStream() ) ); out = new PrintWriter( clientSock.getOutputStream(), true );

The client is processed by a call to processClient(), which contains the application- specific coding. Almost all the rest of ScoreServer is reusable in different sequential servers.

When processClient() returns, the communication has finished and the client link can be closed:

clientSock.close();

The call to saveScores() in the HighScores object is a precautionary measure: it saves the high scores list to a file, so data will not be lost if the server crashes.

Most of the code inside the constructor is inside a try-catch block, to handle IO and network exceptions.

processClient() deals with message extraction from the input stream, which is complicated by having to deal with link termination.

The connection may close because of a network fault, which is detected by a null being returned by the read, or be signaled by the client sending a “bye” message. In both cases, the loop in processClient() finishes, passing control back to the ScoreServer constructor.

private void processClient(BufferedReader in, PrintWriter out) { String line; boolean done = false; try { while (!done) { if((line = in.readLine()) == null)

The ScoreClient Class

The ScoreClient class seems complicated because of its GUI interface. Figure 7 shows a ScoreClient object.

Figure 7. A ScoreClient Object.

The large text area is represented by the jtaMesgs object. There are two text fields for entering a name and score. Pressing enter in the score field will trigger a call to actionPerformed() in the object, as will pressing the “Get Scores” button.

ScoreClient calls makeContact() to instantiate a Socket object for the server at its specified IP address and port. When the connection is made, input and output streams are layered on top of its socket.

: private static final int PORT = 1234; // server details private static final String HOST = "localhost";

private Socket sock; private BufferedReader in; // i/o for the client private PrintWriter out; :

private void makeContact() { try { sock = new Socket(HOST, PORT); in = new BufferedReader( new InputStreamReader( sock.getInputStream() ) ); out = new PrintWriter( sock.getOutputStream(), true ); } catch(Exception e) { System.out.println(e); } }

“localhost” is given as the server’s host name, since the server is running on the same machine as the client. “localhost” is a loopback address and can be employed even when the machine is disconnected from the internet, although the TCP/IP protocol

must be set up in the OS. On most systems (including Windows), it is possible to enter the command “ping localhost” to check the functioning of the loopback.

actionPerformed() differentiates between the two kinds of user input:

public void actionPerformed(ActionEvent e) // Either a name/score is to be sent or the "Get Scores" // button has been pressed { if (e.getSource() == jbGetScores) sendGet(); else if (e.getSource() == jtfScore) sendScore(); }

sendGet() shows how the client sends a message to the server (in this case a “get” string), and waits for a response (a “HIGH$$...” string), which it displays in the text area.

private void sendGet() { // Send "get" command, read response and display it // Response should be "HIGH$$ n1 & s1 & .... nN & sN & " try { out.println("get"); String line = in.readLine(); System.out.println(line); if ((line.length() >= 7) && // "HIGH$$ " (line.substring(0,6).equals("HIGH$$"))) showHigh( line.substring(6).trim() ); // remove HIGH$$ keyword and surrounding spaces else // should not happen jtaMesgs.append( line + "\n"); } catch(Exception ex) { jtaMesgs.append("Problem obtaining high scores\n"); System.out.println(ex); } }

An Simple Alternative Client

Since the client is communicating with the server using TCP/IP, it is possible to replace the client with the telnet command:

telnet localhost 1234

This will initiate a TCP/IP link at the specified host address and port, where the server is listening. The advantage is the possibility of testing the server without writing a client. The disadvantage is that the user must type the messages directly, without the help of a GUI interface. Figure 9 shows a telnet window after the server has responded to a “get” message.

Figure 9. A Telnet Client.

It may be necessary to switch on the ‘local echo’ feature in telnet’s preferences dialog before user typing (e.g. the “get” message) is seen on screen.

4.2. TCP Client and Multithreaded Server

The ScoreServer class is inadequate for real server-side applications because it can only deal with a single client at a time. The ThreadedScoreServer class described in this section solves that problem by creating a thread (a ThreadedScoreHandler object) to process each client who connects. Since a thread interacts with each client, the main server is free to accept multiple connections. Figure 10 shows this in diagram form.

Figure 10. Clients and Multithreaded Server.

ScoreClient objects

Threaded ScoreServer 1234

Threaded ScoreHandler objects

network links

HighScores object

The ScoreClient class need not be changed: a client is unaware that it is talking to a thread.

The HighScores object is referenced by all the threads (indicated by the dotted lines in Figure 10) so that the scores can be read and changed. The possibility of change means that the data inside HighScores must be protected from concurrent updates by two or more of the threads, and from an update occurring at the same time as the scores are being read. These synchronization problems are quite easily solved, as explained below.

ThreadedScoreServer is simpler than its sequential counterpart, since it no longer processes client requests. It consists only of a constructor which sets up a loop waiting for client contacts, handled by threads:

public ThreadedScoreServer() { hs = new HighScores(); try { ServerSocket serverSock = new ServerSocket(PORT); Socket clientSock; String cliAddr;

while (true) { System.out.println("Waiting for a client..."); clientSock = serverSock.accept(); cliAddr = clientSock.getInetAddress().getHostAddress(); new ThreadedScoreHandler(clientSock, cliAddr, hs).start(); } } catch(Exception e) { System.out.println(e); } } // end of ThreadedScoreServer()

Each thread gets a reference to the client’s rendezvous socket and the HighScores object.

ThreadedScoreHandler contains almost identical code to the sequential ScoreServer class; for example, it has processClient() and doRequest() methods. The main difference is the run() method:

public void run() { try { // Get I/O streams from the socket BufferedReader in = new BufferedReader( new InputStreamReader( clientSock.getInputStream() ) ); PrintWriter out = new PrintWriter( clientSock.getOutputStream(), true );

processClient(in, out); // interact with a client

// Close client connection clientSock.close(); System.out.println("Client (" + cliAddr +