For the past two weeks I've been studying how to use threads and sockets in Java.
And as a practice of the stuff I learned, this week I made a very basic console chat application.
The source code can be seen here.
What I've made
This chat application works by running two programs, a server program and a client program.
Here's how it works:
- Run the server program specifying a port number and wait for a client to connect.
- Run the client program specifying the clients name, the IP address of the server, and the port number.
- If the connection is successful, there will be a message that tells you so, and then you're able to chat.
- You can disconnect by sending "bye".
You can see how the actual operation looks like from the following link:
How I made it
Here's a list of classes and methods I mainly used:
- Sockets
- Threads
- BufferedReader
- InputStreamReader
- getInputStream
- PrintWriter
- getOutputStreams
I used sockets to manage the connection between the server side application and the client side application.
I created two threads: one for receiving message and another one for sending message. By having two separate threads for receiving and sending messages, both operations can be executed simultaneously. To be more clear, if there was only one thread that does both receiving and sending, whenever a message is received, the program would have to wait until it sends out a message in order to receive another message, and vise versa. This was actually a problem i faced while I was creating this application. I solved this problem by running the receiving thread and the sending thread at the same time.
Now here is how receiving and sending messages specifically work:
Receiving Messages: With the combination of BufferedReader, InputStreamReader and getIntputStream, the thread reads the input sent from the other side and buffers it. Then it prints it on the screen while the readLine() method does not return null.
Sending Messages: Using BufferedReader along with InputStreamReader, it reads its own input and sends it to the other side's screen using the PrintWriter.
If you're curious, try out my application by cloning the source code shown above into your computer. You can even run the server app and the client app on different computers and still have a chat, since you are able to specify the port number when running the server app, and IP address and port number when running the client app.
Feel free to ask me in the comment section below if you have any questions. Thanks for reading!