http://www.dreamincode.net/forums/topic/259777-a-simple-chat-program-with-clientserver-gui-optional/
Many times in the forum we see questions about Chat programs which imply:
- TCP connections
- Threads
- and a GUI most of the times
So here is a very simple Chat program from which you can inspire yourself. The most important point is to give you code
examples to which we will be able to refer you when you will have a problem in your code.
The code contains 5 classes that you can cut & paste in a directory on your PC and it should work.
The 5 classes are:
- ChatMessage.java
- Server.java
- Client.java
- ServerGUI.java
- ClientGUI.java
Actually, if you want to run the application in console mode, you only need the first 3 classes. The two GUI classes can be used as a bonus, it is a very simple GUI. You can run both the Client and the Server in GUI mode or only one of the two in GUI mode.
The ChatMessage class.
When you establish connections over TCP it is only a serie of bytes that are actually sent over the wire. If you have a Java application that talks to a C++ application you need to send series of bytes and have both the sender and the receiver to agree on what these bytes represent.
When talking between two Java applications, if both have access to the same code, I personally prefer to send Java Object between the two applications. Actually it will still a stream of bytes that will be sent over the internet but Java will do the job of serializing and deserializing the Java objects for you. To do that you have to create an ObjectInputStream and an ObjectOutputStream from the Socket InputStream and the Socket OutputStream.
The objects sent of the sockets have to implements Serializable.
In this application, all the messages sent from the Server to the Client are String objects. All the messages sent from the Client to the Server (but the first one which is a String) are ChatMessage. ChatMessage have a type and a String that contains the actual message.
ChatMessage.java
08 | public class ChatMessage implements Serializable { |
10 | protected static final long serialVersionUID = 1112122200L; |
16 | static final int WHOISIN = 0 , MESSAGE = 1 , LOGOUT = 2 ; |
18 | private String message; |
21 | ChatMessage( int type, String message) { |
23 | this .message = message; |