A Basic Chat Program In Java Using Sockets

The design and structure and helpful tips when writing a chat module in java

© SolutionLibrary Inc. solutionlibary.com 9836dcf9d7 https://solutionlibrary.com/computer-science/software-development/a-basic-chat-program-in-java-using-sockets-35i

Solution Preview

...rom the server must be a continuous process,
ie it has to be within an infinite loop. Any part of you program which must be in an infinite loop has to be a Thread

Server program:

The server program will do the following.
CONSTANTLY look out for any new Client who wants to connect to the server.
Constantly listen to each existing client, for any messages it may send, and also correspondingly send it to the appropriate

Here are the steps and some small pieces of critical code:

Client Program

1. Establish a connection

Socket socClient=new Socket("server url",int portNumber);

2. Once the socket is made
The client will start a thread
and will constantly listen for any message to the server

BufferedReader br=
new BufferedReader(new InputStreamreader(socClient.getInputStream));

String messageRead=br.readLine();

It will display the message appropriately.

3. The client can send a message to the server
In the following way

PrintWriter pw=new PrintWriter(socClient.getOutputStream());
pw.println("message to be sent");

the program takes the input from the user usually through a GUI
in which case the user will type the message in a text box and press the send button or the enter key.
the corresponding event will be handled with event handlers, and the required text obtained, will be sent thought
the pw.println();command

If not using a gui the client program will take inputs from ...