In this class we will create a peer-to-peer chat program using Java sockets.
Protocol:
User A connects to user B.
User B sends the list of other users it is connected to.
User A sends its listening port or address.
User A can send textual messages to other users directly.
Exercises:
Create the class Endpoint
that stores an IP address-port pair. Its fields are an InetAddress
and an int
.
Write a constructor that takes a string as argument in the following format: "ipaddress:port"
.
Create a class ChatSession
.
The class should have a method getEndpoint
that accesses the ip address and port number of the connected client.
It should also have a method start
that starts the session. First, it should send the list of endpoints also connected to this server. Next, it should receive the new endpoint and notify the client to connect to that endpoint.
Create a class ChatClient
.
The class should have a method listen
that takes a port number and accepts connections on that port using ServerSocket
. In an infinite loop, it accepts connections and creates new objects of ChatSession
to handle them. It also stores the sessions.
The class should also have a method getEndpoints
that returns the endpoints of all sessions. This is useful for handling incoming connections new clients.
The class should store the sockets of other connected users.
The class should have a method connectTo
, that takes an endpoint and opens a socket connection if no socket connection had been established to that endpoint. It should also perform the initial message exchange that constitute reception of other clients and sending its own endpoint.
After the connection is established, it should read lines from command line and send each line to connected clients.
Create a method main
that starts the client.