240-322 cli/serv.: chat/121 client/server distributed systems v objectives –discuss a...

36
0-322 Cli/Serv.: Chat/12 Client/Server Distributed Client/Server Distributed Systems Systems Objectives Objectives discuss a client/server based chat discuss a client/server based chat system system mention two other ways of chatting mention two other ways of chatting 240-322, Semester 1, 2005-2006 12. Java Chat

Upload: flora-shaw

Post on 30-Dec-2015

266 views

Category:

Documents


0 download

TRANSCRIPT

240-322 Cli/Serv.: Chat/12 1

Client/Server Distributed SystemsClient/Server Distributed Systems

ObjectivesObjectives– discuss a client/server based chat systemdiscuss a client/server based chat system– mention two other ways of chattingmention two other ways of chatting

240-322, Semester 1, 2005-2006

12. Java Chat

240-322 Cli/Serv.: Chat/12 2

ContentsContents

1.1. Chat CharacteristicsChat Characteristics

2.2. Threaded TCP Client/Server ChatThreaded TCP Client/Server Chat

3.3. Other ApproachesOther Approaches

240-322 Cli/Serv.: Chat/12 3

1. Chat Characteristics1. Chat Characteristics

Client/Server or P2PClient/Server or P2P

server

clients

messages

clients

continued

240-322 Cli/Serv.: Chat/12 4

Any number of clients.Any number of clients. Clients can join/depart at any time.Clients can join/depart at any time. There's no ordering to the communicationThere's no ordering to the communication

– anyone can talk at any timeanyone can talk at any time– a message can arrive at a client at any timea message can arrive at a client at any time– a message can be sent by a client at any timea message can be sent by a client at any time

240-322 Cli/Serv.: Chat/12 5

1.1 Chatting Compared to Games1.1 Chatting Compared to Games

Typical games are chess, monopoly, tic-tac-Typical games are chess, monopoly, tic-tac-toe. These types of games have:toe. These types of games have:– a fixed number of playersa fixed number of players– the game starts only when all the players are the game starts only when all the players are

presentpresent– the players take fixed turnsthe players take fixed turns

continued

240-322 Cli/Serv.: Chat/12 6

But chatting is similar to multiplayer online But chatting is similar to multiplayer online games (MMOGs) such as games (MMOGs) such as City Of HeroesCity Of Heroes, , RagnarokRagnarok..

The chat communication model is used by The chat communication model is used by MMOGs.MMOGs.

240-322 Cli/Serv.: Chat/12 7

1.2. Advantages of a Server Model1.2. Advantages of a Server Model

Client controlClient control– e.g. a server can filter client messagese.g. a server can filter client messages

ManagementManagement– e.g. login/logout, message routing, billinge.g. login/logout, message routing, billing

Resource StorageResource Storage– e.g. message logs, images, movies, soundse.g. message logs, images, movies, sounds

These features are harder to support in P2P.These features are harder to support in P2P.

240-322 Cli/Serv.: Chat/12 8

1.3. Disadvantages of a Server Model1.3. Disadvantages of a Server Model

A single point of failure.A single point of failure. A communications bottleneck.A communications bottleneck. Increased message latency.Increased message latency.

Many of these problems are solved by using Many of these problems are solved by using P2P, P2P, oror by using multiple servers. by using multiple servers.

240-322 Cli/Serv.: Chat/12 9

1.4. More Information1.4. More Information

The examples in these slides come from:The examples in these slides come from:Killer Game Programming in JavaKiller Game Programming in Java (KGPJ) (KGPJ)Chapter 30Chapter 30http://fivedots.coe.psu.ac.th/~ad/jg/ch19http://fivedots.coe.psu.ac.th/~ad/jg/ch19

A draft of the chapter, and all the code, can A draft of the chapter, and all the code, can be found there.be found there.

240-322 Cli/Serv.: Chat/12 10

2. Threaded TCP Client/Server Chat2. Threaded TCP Client/Server Chat

continued

240-322 Cli/Serv.: Chat/12 11

2.1. Client Classes2.1. Client Classes

ChatClientChatClient– maintains the GUI, processes the user's input, maintains the GUI, processes the user's input,

and sends messages to the server over a TCP and sends messages to the server over a TCP linklink

ChatWatcherChatWatcher– waits for messages from the server, and waits for messages from the server, and

displays them in ChatClient's GUI text areadisplays them in ChatClient's GUI text area

240-322 Cli/Serv.: Chat/12 12

2.2. Client-side Messages2.2. Client-side Messages

ChatClient can send the following messagesChatClient can send the following messages::– who– bye

– any text message

server

messages

client

240-322 Cli/Serv.: Chat/12 13

2.3. Server Classes2.3. Server Classes

ChatServerChatServer– the top-level server, which spawns a the top-level server, which spawns a

ChatServerHandler thread when a new client ChatServerHandler thread when a new client connects to itconnects to it

ChatServerHandlerChatServerHandler– handles the communication with a clienthandles the communication with a client

ChatGroupChatGroup– holds client details (e.g. input streams), accessible holds client details (e.g. input streams), accessible

via synchronized methodsvia synchronized methods

240-322 Cli/Serv.: Chat/12 14

2.4. Server-side Messages2.4. Server-side Messages

WHO$$ cliAddr1 & port1 & ... cliAddrN & portN &

– sent back to a client in response to a "who" message

(cliAddr, port): message – broadcast to all the clients

server

messages

clients

240-322 Cli/Serv.: Chat/12 15

2.5. ChatClient2.5. ChatClient sends thebye message

sends thewho message

sends a textmessage

showsmessagesreceivedfrom theserver

240-322 Cli/Serv.: Chat/12 16

Contacting the ServerContacting the Server

// globals// server detailsprivate static final int PORT = 1234; private static final String HOST = "localhost";

private Socket sock;private PrintWriter out; // output to the server

continued

240-322 Cli/Serv.: Chat/12 17

private void makeContact(){ try { sock = new Socket(HOST, PORT); BufferedReader in = new BufferedReader(

new InputStreamReader( sock.getInputStream()) ); out = new PrintWriter(sock.getOutputStream(),true );

new ChatWatcher(this, in).start(); // watch for server msgs } catch(Exception e) { System.out.println(e); }}

240-322 Cli/Serv.: Chat/12 18

2.6. ChatWatcher Thread2.6. ChatWatcher Thread

run() {

// wait for message // process it // show in GUI

}

from server

WHO$$,broadcast msg

ChatWatcher(on client-side)

continued

looping

240-322 Cli/Serv.: Chat/12 19

while ((line = in.readLine()) != null) { if ((line.length() >= 6) && // "WHO$$ " (line.substring(0,5).equals("WHO$$"))) showWho( line.substring(5).trim() );

// remove WHO$$ keyword and spaces else // show immediately client.showMsg(line + "\n");}

240-322 Cli/Serv.: Chat/12 20

2.7. ChatServer2.7. ChatServer

// wait for client connection // create handler for client

port1234

ChatServer(on the server-side)

clientconnections

continued

looping

240-322 Cli/Serv.: Chat/12 21

public ChatServer(){ cg = new ChatGroup(); try { ServerSocket serverSock = new ServerSocket(PORT); Socket clientSock; while (true) { System.out.println("Waiting for a client..."); clientSock = serverSock.accept(); new ChatServerHandler(clientSock, cg).start(); } } catch(Exception e) { System.out.println(e); }}

240-322 Cli/Serv.: Chat/12 22

2.8. ChatServerHandler2.8. ChatServerHandler

A handler is created for each client that A handler is created for each client that contacts the server.contacts the server.

The handler is a thread that processes all the The handler is a thread that processes all the clients interaction with the server.clients interaction with the server.

continued

240-322 Cli/Serv.: Chat/12 23

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);

cg.addPerson(cliAddr, port, out); // add client to ChatGroup

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

continued

240-322 Cli/Serv.: Chat/12 24

// the client has finished when execution // reaches here cg.delPerson(cliAddr, port); // remove client details clientSock.close(); System.out.println("Client (" + cliAddr + ", " + port + ") connection closed\n"); } catch(Exception e) { System.out.println(e); }}

240-322 Cli/Serv.: Chat/12 25

processClient()processClient()

A loop which:A loop which:– waits for a message from the clientwaits for a message from the client– processes the message, using doRequest()processes the message, using doRequest()– if a response (or broadcast) is needed, it is if a response (or broadcast) is needed, it is

carried out by the ChatGroup objectcarried out by the ChatGroup object

continued

240-322 Cli/Serv.: Chat/12 26

private void doRequest(String line, PrintWriter out){ if (line.trim().toLowerCase().equals("who")) { System.out.println("Processing 'who'"); out.println( cg.who() ); } else // use ChatGroup object to broadcast message cg.broadcast( "("+cliAddr+", "+port+"): " + line);}

cg is the ChatGroup object

240-322 Cli/Serv.: Chat/12 27

2.9. ChatGroup2.9. ChatGroup

Stores client details in Chatter objectsStores client details in Chatter objects– 1 Chatter object per client1 Chatter object per client– details include client input streamdetails include client input stream

Answers "who" messages.Answers "who" messages. Handles broadcasting.Handles broadcasting.

ChatGroup uses synchronized methods to ChatGroup uses synchronized methods to control access to the clients streams.control access to the clients streams.

continued

240-322 Cli/Serv.: Chat/12 28

240-322 Cli/Serv.: Chat/12 29

Why is ChatGroup Synchronized?Why is ChatGroup Synchronized?

240-322 Cli/Serv.: Chat/12 30

A ChatGroup MethodA ChatGroup Method

synchronized public void broadcast(String msg){ Chatter c; for(int i=0; i < chatPeople.size(); i++) { c = (Chatter) chatPeople.get(i); c.sendMessage(msg); }} // end of broadcast()

240-322 Cli/Serv.: Chat/12 31

2.10. The Chatter Class2.10. The Chatter Class

A Chatter object manages a client's address, A Chatter object manages a client's address, port and a PrintWriter stream going to the clport and a PrintWriter stream going to the client.ient.

private PrintWriter out; // global

public void sendMessage(String msg){ out.println(msg); }

240-322 Cli/Serv.: Chat/12 32

3. Other Approaches3. Other Approaches

Chapter 30 in KGPJ contains two other chat Chapter 30 in KGPJ contains two other chat implementations, using:implementations, using:– UDP multicasting (a form of P2P)UDP multicasting (a form of P2P)– a servlet servera servlet server

240-322 Cli/Serv.: Chat/12 33

3.1. UDP Multicasting Clients 3.1. UDP Multicasting Clients and a Name Serverand a Name Server

continued

240-322 Cli/Serv.: Chat/12 34

Not pure P2P -- it uses a login name server.Not pure P2P -- it uses a login name server.

NameServer deals with NameServer deals with whowho messages messages– reduces the packets volume in the multicast reduces the packets volume in the multicast

groupgroup

Main problemMain problem: there's no easy way to : there's no easy way to control access to the multicast group.control access to the multicast group.

240-322 Cli/Serv.: Chat/12 35

3.2. Servlet as a Server3.2. Servlet as a Server

continued

240-322 Cli/Serv.: Chat/12 36

The key difference between this approach and The key difference between this approach and the standard client/server is that ChatServlet the standard client/server is that ChatServlet cannot start communicationcannot start communication with a client. with a client.– URLChatWatcher URLChatWatcher must periodically pollmust periodically poll the the

ChatServlet for messagesChatServlet for messages

Since the servlet is contacted using HTTP, it Since the servlet is contacted using HTTP, it will work through most firewalls.will work through most firewalls.