Transcript ppt
A Chat Server
DBI – Representation and
Management of Data on the Internet
A Chat Server Example
• Gives an example of how to combine the
client and the server application into one
combined system
• The Chat application gives a group of
remote users the ability to ‘talk’ to each
other through a server
A Real Chat Room
Commercials advertisements
Chat Server
•
•
•
•
•
Listens on a port
Accepts connections
Spawns threads, one per connection
Receives a message from one client
Dispatches it to all clients
The Objects of the Server
• ChatServer
– main
• ClientHandler
– one per connection
– threaded
• Dispatcher
– vector
Chat Server Objects (Diagram)
ChatServer
Dispatcher
ClientHandler
Socket
ClientHandler
Socket
ClientHandler
• In the running loop:
– Generates filter streams
– Reads a message line
– Sends the messages to the dispatcher
• On another client message:
– Get the message from the dispatcher
– Sends the message to the client using the socket
to the client
Dispatcher
• Keeps a list of all client handlers
• On a client message (sends the message to
all clients):
– Accepts a String and an identifying integer
– Enumerates down all client handlers and calls
each one’s send() method
ChatServer
•
•
•
•
Creates a new ServerSocket
Creates a new Dispatcher
Listens for connections
When connection received, creates a new
ClientHandler and starts it as a new thread
• Adds it to the Dispatcher
The Code
ChatClient.java
ChatServer.java
ClientHandler.java
Dispatcher.java