n part 1
of this article, you saw how to build your own instant messenger application that allows many users to chat simultaneously. While the application is interesting, it is not very flexible as you cannot choose the user(s) you want to chat with; all messages are broadcasted to everyone in the chat.
Building on the earlier article, I'll show you how to enhance the application to allow private chats between selected users. You will also build FTP support into the application so that you can transfer files between users.
Defining Your Own Protocol
In order to enhance the chat application, you have to define your own protocol for the various functions. For example, when you want to chat with someone, you need to indicate the user name to the server so that only messages destined for this user are sent to him. Similarly, when you need to perform a file transfer, there must be several handshaking processes to ensure that the recipient explicitly accepts the file transfer before it is sent.
This section describes the communication between the users and the server.
User1 signs in to the server:
- User1 sends [Join][User1] to the server indicating its presence
- Server broadcast [Join][User1] to all the users currently connected
Requesting users' names
When User1 logs in to the server, he needs to know who is currently online:
- User1 sends [Usrs] to the server, asking for a list of users currently online
- Server sends back to User1 [Usrs][User1,User2,UserN,] containing a list of all user names
User1 wants to chat with User2 and User3:
- User1 sends [Talk][User2,User3,]User1>Hello! to server
- Server sends [Talk][User2,User3,]User1>Hello! to both User2 and User3
User1 (IP address 220.127.116.11) wants to send a file named File1.txt to User2 (IP address 18.104.22.168):
- User1 sends [File][User1,User2,][File1.txt] to server
- Server sends [File][User1][File1.txt] to User2 to confirm if he wants to receive the file
- If User2 responds with Yes, server sends [Send_File][User1, User2] to server indicating that it wishes to receive the file
- User2 starts to listen at port number 501 for incoming data
- Server looks up the IP address of User2 and sends [Send_File][22.214.171.124] to User1
- User1 starts the FTP service by using the IP address (126.96.36.199), port number 501.
|Author's Note: Note that for file transfer, the actual transferring of files takes place between the clients; the server is not involved.
Leaving a chat
User1 signs out of the chat:
- User1 sends [Left][User1] to the server
- Server will broadcast [Left][User1] to all users